日期:2014-05-16  浏览次数:20562 次

请教一个linux 线程编程问题
本帖最后由 lixiang201101 于 2013-10-21 22:10:49 编辑
/*************************************************************************
> File Name: exc.c
> Author: ma6174
> Mail: ma6174@163.com 
> Created Time: 2013年10月19日 星期六 18时35分46秒
 ************************************************************************/

#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/wait.h>
int main(void)
{
pid_t ch,ch1,ch2;
ch1=fork();
ch2=fork();

if(ch1==-1)
{
printf("error\n""");
exit(1);
}

else if(ch1==0)
{
printf("In ch1 :execute ' ls -l'\n");
if(execlp("ls","ls","-l",NULL)<0)
perror("ch1 execlp\n");
exit(1);
}

if(ch2==-1)
{
printf("ch2 fork");
exit(1);
}

else if(ch2==0)
{
printf("ch2 will sleep for about 5 seconds\n");
sleep(5);
exit(0);
}

else
{
printf("In father process:\n");
do
{
ch=waitpid(ch2,NULL,WNOHANG);
if(ch==0)
{
printf("The child2 process has not exited!\n");
sleep(1);
}
}while(ch==0);
if(ch==ch2)
printf("Get ch2\n");
else
printf("Error occured\n");
}
}


我在ubuntu上通过编译后在桌面上执行出来如下
root@lx-virtual-machine:~/桌面# ./exec
In father process:
The child2 process has not exited!
ch2 will sleep for about 5 seconds
In ch1 :execute ' ls -l'
In ch1 :execute ' ls -l'
总用量 28
总用量 28
drwxr-xr-x 2 root root 4096 10月 17 22:14 2-4
drwxr-xr-x 2 root root 4096 10月 21 20:51 2-5
-rwxrw-rw- 1 root root 1051 10月 19 18:50 exc.c
-rwxr-xr-x 1 root root 7625 10月 21 21:38 exec
drwxrwxrwx 2 root root 4096 10月 14 20:57 File
drwxrwxrwx 2 root root 4096 10月 17 15:53 Time
lrwxrwxrwx 1 root root    9 10月 13 22:17 到 hgfs 的链接 -> /mnt/hgfs
drwxr-xr-x 2 root root 4096 10月 17 22:14 2-4
drwxr-xr-x 2 root root 4096 10月 21 20:51 2-5
-rwxrw-rw- 1 root root 1051 10月 19 18:50 exc.c
-rwxr-xr-x 1 root root 7625 10月 21 21:38 exec
drwxrwxrwx 2 root root 4096 10月 14 20:57 File
drwxrwxrwx 2 root root 4096 10月 17 15:53 Time
lrwxrwxrwx 1 root root    9 10月 13 22:17 到 hgfs 的链接 -> /mnt/hgfs
The child2 process has not exited!
The child2 process has not exited!
The child2 process has not exited!
The child2 process has not exited!
Get ch2
 在这里我就有问题了,
问题一:进程在经过了两个fork之后加上主进程数应该四四格进程吧?
问题二:为什么会出现两个
In ch1 :execute