我写这段代码: http://ideone.com/cNypUb
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
void signchld (int signal){
fprintf (stderr, "[X] child exited\n");
}
int main(){
signal (SIGCHLD, signchld);
int i;
for(i=0;i<=300;i++){
pid_t f;
f=fork();
if(f==0){
//child
usleep(3*1000000);
fprintf (stderr, "[C1] %d\n",i);
exit(0);
fprintf (stderr, "[C2] %d\n",i);
}else if(f>0){
fprintf (stderr, "[P1] %d\n",i);
usleep(20000000);
fprintf (stderr, "[P2] %d\n",i);
}
}
return 0;
}
但是 [p2]
每 3 秒运行一次,然后运行下一个循环
我希望看到这个输出:
[P1] 0
[C1] 0
[X] child exited
20秒后
[P2] 0
[P1] 1
[C1] 1
[X] child exited
最佳答案
是信号处理程序 signchld()
中断了父级中的 usleep()
,我们可以通过代入来证明
usleep(20000000);
与
if (usleep(20000000) < 0) {
if (errno == EINTR)
fprintf (stderr, "[PX] usleep() interrupted by a signal\n");
}
(当然包括 errno.h
)。这将打印
[P1] 0
[C1] 0
[X] child exited
[PX] usleep() interrupted by a signal
[P2] 0
[P1] 1
等等。
在我的系统 (GNU/Linux) 上,usleep()
的手册页内容如下:
4.3BSD, POSIX.1-2001. POSIX.1-2001 declares this function obsolete; use nanosleep(2) instead. POSIX.1-2008 removes the specification of usleep().
Only the EINVAL error return is documented by SUSv2 and POSIX.1-2001.
关于c - fork 和 usleep 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23255042/