当我在 x86-64 linux 上使用 libc 的 system() 函数时,我注意到一个非常奇怪的行为,有时调用system()失败并出现分段错误,这是我在使用gdb.
我注意到在这一行中出现了分段错误:
=> 0x7ffff7a332f6 <do_system+1094>: movaps XMMWORD PTR [rsp+0x40],xmm0
Run Code Online (Sandbox Code Playgroud)
根据手册,这是 SIGSEGV 的原因:
当源或目标操作数是内存操作数时,操作数必须在 16 字节边界上对齐,否则会生成通用保护异常 (#GP)。
再往下看,我注意到我的rsp值确实不是 16 字节填充的(也就是说,它的十六进制表示没有以 结尾0)。rsp在调用之前手动修改权限system实际上使一切正常。
所以我写了以下程序:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
register long long int sp asm ("rsp");
printf("%llx\n", sp);
if (sp & 0x8) /* == 0x8*/
{
printf("running system...\n");
system("touch hi");
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
用gcc 7.3.0编译,果然,观察输出时:
sha@sha-desktop:~/Desktop/tda$ ltrace -f ./o_sample2 …Run Code Online (Sandbox Code Playgroud) 我有以下代码:
public static boolean turn = true;
public static void main(String[] args) {
Runnable r1 = new Runnable() {
public void run() {
while (true) {
while (turn) {
System.out.print("a");
turn = false;
}
}
}
};
Runnable r2 = new Runnable() {
public void run() {
while (true) {
while (!turn) {
System.out.print("b");
turn = true;
}
}
}
};
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
}
Run Code Online (Sandbox Code Playgroud)
在课堂上,我们了解了使用未同步代码时可能出现的"可见性"问题.据我所知,为了节省时间,编译器将决定抢占turnCPU中的缓存,这意味着线程不会知道turnRAM中是否更改了值,因为他没有检查它.
根据我的理解,我希望代码运行如下: …