需要根据 fork() 的返回值来判断下面的代码是在父进程(返回pid>0)中还是子进程(返回0)中. 像上面的代码中 if 中的代码被在子进程中执行, else 中的代码在父进程中执行。
2、例程:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
pid_t id //定义一个进程号变量
int i=0
printf("start fork/n")
id = fork() //调用fork函数新建一个进程
i ++
printf("end fork/n")
//判断当前进程
if(id <0){//出错
perror("fork failed/n")
exit(1)
}
else if(id == 0){//子进程
printf("In child/n")
printf("i = %d/n", i++)
exit(0)
}
else{//父进程
printf("In father/n")
printf("i = %d/n", i++)
exit(0)
}
return 0
}
}
else if(WIFEXITED(status))
{
printf(")
while(((child=wait(&status))==-1)&(errno==EINTR))
exit(1).h>Fork Error,strerror(errno))*请解释一下*/
if((child=fork())==-1)
{
printf("
#include<I am the child
int main(int argcn"n".h>:%d\,strerror(errno)).h>
printf(",getpid())1000000!status)
{
printf("n".h>
int status.h>sys/errno
exit(i)n"wait,WEXITSTATUS(status)),child)
#include<*请解释一下*/
if(child==-1)
{
printf("Child %d terminated normally return status is %d\
}
else if(i<:%s\n"
i=5.h>,childn"Child %d terminated due to signal %d znot caught\
printf("sys/I exit with%d\mathstdio
#include<
printf("n"
#include<
}
else if(child==0)
{
int i=0
}
/
}
else if(WIFSIGNALED(status))
{
printf("types:%s"unistd,i),char **argv)
{
pid_t child
/Child %d terminated normally return status is zero\Wait ErrorThis will demostrate how to get the child status\
for(i=0i++)
#include<,WTERMSIG(status))
}
return 0能不能帮忙解释一下这段代码中的一部分
#include<,child
/*请解释一下*/while(((child=wait(&status))==-1)&(errno==EINTR))
这种的目的是父亲进程等待子进程结束,并回收子进程的资源,将子进程的退出状态存储在status中,同时,返回该子进程的pid。
如果wait函数返回-1表示wait函数被其它情况打断返回,并没有等待到子进程结束,而同时判断errno的值是不是EINTR(意思是让你try again),那么,让进程继续等待。因为这个错误并不是真正wait错误,而是被timeout时间等造成的,因此重新等待。而如果是其它情况,显然是wait函数调用错误,即下面的if(child==-1),需要打印错误信息。‘
//但你这句应该写错了。应该是逻辑与而不是位与 *** 作。即
while(((child=wait(&status))==-1)&&(errno==EINTR))
/*请解释一下*/
if(child==-1)
你对信号处理部分还需要努力。
另外介绍一本书《Linux高级程序设计 第3版》 上面讲得很清楚。
有问题我们继续交流,一起学习。
更多技术文章可以关注我的微博,名字:成都睿尔科技 。
getpid()得到当前进程的pid, getppid()是得到父进程的pid写成语句就是
printf ( "My process ID is%d\n", getpid())
printf ( "My parent's process ID is%d\n", getppid())
记得要添加头文件 #include <stdio.h>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)