我觉得我的代码将无法打印文本system()在里面做一个像sem_post这样的调用吗?
哦,为什么来这里!\ n
,但它确实。
system()
有什么不对吗?因为当我删除它时,代码就会按我的意愿运行,停止运行。
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
pthread_t id0, id1;
sem_t sp;
void *fun0(void *) {
// When erasing the following line "system("");",
// it block up, and doesn't print "oh why come here!\n".
// But with it, it print the text!
system("");
return NULL;
}
void *fun1(void *) {
sem_wait(&sp);
fprintf(stderr, "oh why come here!\n");
return NULL;
}
int main() {
sem_init(&sp, 0, 0);
pthread_create(&id0, 0, fun0, NULL);
pthread_create(&id1, 0, fun1, NULL);
void *stat0, *stat1;
pthread_join(id0, &stat0);
pthread_join(id1, &stat1);
return 0;
}
编译器:GCC 4.1.2 Linux内核:2.6.18
我用gcc 4.6.3,内核3.2.0编译它,它跑了,我想也是。 所以我认为这是因为gcc 4.1.2或kernel 2.6.18。
这怎么可能是正确答案?如果sem_wait被阻塞,那么下面的printf不会发生。会发生什么情况是,执行system()的线程会触发一个中断sem_wait的信号(可能是SIGCHILD?)。检查sem_wait的返回值,你会被修复(如果我是对的,它是-EINTR)。 – xryl669 2013-06-28 16:50:00
你移动这些printf()语句,你会明白为什么。 – 2013-06-28 17:07:40