#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void)
{
pid_t Checksum_pid = fork();
if (Checksum_pid < 0)
printf("Fork Failed\n");
else if (Checksum_pid == 0)
{
printf("\nInside Child Process before execl");
//execl("/bin/sleep", "/bin/sleep", "2", NULL);
execl("/bin/ls","ls",(char *)NULL) ;
//exit(EXIT_FAILURE);
printf("\nInside Child Process after execl\n");
exit(EXIT_FAILURE);
}
else
{
int childStatus;
printf("\nInside Parent Process");
sleep(5);
pid_t returnValue = waitpid(Checksum_pid, &childStatus, WNOHANG);
if (returnValue > 0)
{
if (WIFEXITED(childStatus))
printf("\nChild Exit Code: %d\n", WEXITSTATUS(childStatus));
else
printf("\nChild Exit Status: 0x%.4X\n", childStatus);
}
else if (returnValue == 0)
printf("\nChild process still running\n");
else
{
if (errno == ECHILD)
printf("\nError ECHILD!!\n");
else if (errno == EINTR)
printf("\nError EINTR!!\n");
else
printf("\nError EINVAL!!\n");
}
printf("\nParent: I am about to finish\n");
}
return 0;
}
輸出:打印不輸出可見
kth4kor-2:~/bosch/Test1$ ./a.out a.out ___waitpid_test1 waitpid_test1~ waitpid_test1.c waitpid_test1.c~ waitpid_test2.c waitpid_test2.c~
Inside Parent Process Child Exit Code: 0
Parent: I am about to finish
,如果我現在將(5)在母體除去睡眠然後輸出:
kth4kor-2:~/bosch/Test1$ ./a.out
Inside Parent Process
Child process still running
Parent: I am about to finish
[email protected]:~/bosch/Test1$ a.out ___waitpid_test1 waitpid_test1~ waitpid_test1.c waitpid_test1.c~ waitpid_test2.c waitpid_test2.c~
最後餘以0嘗試作爲第三個參數waitpid而不是WNOHANG然後它給了我下面的輸出與任何打印的孩子:
kth4kor-2:~/bosch/Test1$ ./a.out
a.out ___waitpid_test1 waitpid_test1~ waitpid_test1.c waitpid_test1.c~ waitpid_test2.c waitpid_test2.c~
Inside Parent Process
Child Exit Code: 0
Parent: I am about to finish
有人可以幫助我理解執行execl之後和執行之前的過程行爲嗎?
除了@Joachim提到的解決方案,您可以使用'setbuf(stdout,NULL)'設置禁用緩衝;'或者在'stderr'上打印您的消息。 –
printf(「\ n在execl之前的子進程\ n」);工作正常... – kapilddit