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

fork、execl创建多进程,出现一个僵死进程
我想要创建num个进程,进程执行的操作是执行batchconvert脚本,并让这些进程并发执行。代码如下:

[code=C/C++][/code]
void createsubprocess(int num)

int i;
int child; //fork返回值
int rtn; //进程状态
int pid[num]; //进程的pid数组
char txtname[128]={0}; //txt文本文件名

for(i=0;i<num;i++)
{
sprintf(txtname , "%02d.txt", i+1); //得到txt文本文件的文件名 
if((child = fork()) == -1)
{
perror("fork");
exit(EXIT_FAILURE);
}
else if(child==0) //子进程执行
{
// pid=getpid(); //这里的不会执行,why?
// printf("in the child process pid = %d", pid); 
if( execl("./batchconvert", "./batchconvert ",txtname, (char *)0 ) == -1 ) 
{ //将txt文件名依次传递给batchconvert脚本
perror("execl");
exit(EXIT_FAILURE);


else //父进程运行

pid=child; //保存子进程的进程号
printf("the child process pid = %d\n", pid);

}
for(i=0;i<num;i++)
{
if(waitpid(pid,NULL,0)!=pid)
perror("waitpid");

}
exit(EXIT_SUCCESS);
}

说明:源文件文件名是source.c,num=9
我有一些疑问,请大家帮我找找原因:
1、子进程里注释的那两行不会执行,不知道怎么回事。
2、整个程序的执行结果是:创建了num个进程,但是最后一个创建的进程是defunct。而且,console还会打印出很多类似环境变量的内容,有点长,如下:

[root@yff c]# gcc source.c -o source
[root@yff c]# ./source
the child process pid[i] = 10066
the child process pid[i] = 10071
the child process pid[i] = 10076
the child process pid[i] = 10078
the child process pid[i] = 10080
the child process pid[i] = 10087
the child process pid[i] = 10092
the child process pid[i] = 10097
BASH=/bin/sh
BASH_ARGC=([0]="1")
BASH_ARGV=([0]="09.txt")
BASH_LINENO=([0]="0")
BASH_SOURCE=([0]="./batchconvert")
BASH_VERSINFO=([0]="3" [1]="1" [2]="17" [3]="1" [4]="release" [5]="i686-redhat-linux-gnu")
BASH_VERSION='3.1.17(1)-release'
CVS_RSH=ssh
DIRSTACK=()
DISPLAY=:0.0
EUID=0
GROUPS=()
G_BROKEN_FILENAMES=1
HISTSIZE=1000
HOME=/root
HOSTNAME=yff
HOSTTYPE=i686
IFS=' 
'
INPUTRC=/etc/inputrc
LANG=zh_CN.UTF-8
LESSOPEN='|/usr/bin/lesspipe.sh %s'
LOGNAME=root
LS_COLORS='no=00:fi=00:di=00;34:ln=00;36:pi=40;33:so=00;35:bd=40;33;01:cd=40;33;01:or=01;05;37;41:mi=01;05;37;41:ex=00;32:*.cmd=00;32:*.exe=00;32:*.com=00;32:*.btm=00;32:*.bat=00;32:*.sh=00;32:*.csh=00;32:*.tar=00;31:*.tgz=00;31:*.arj=00;31:*.taz=00;31:*.lzh=00;31:*.zip=00;31:*.z=00;31:*.Z=00;31:*.gz=00;31:*.bz2=00;31:*.bz=00;31:*.tz=00;31:*.rpm=00;31:*.cpio=00;31:*.jpg=00;35:*.gif=00;35:*.bmp=00;35:*.xbm=00;35:*.xpm=00;35:*.png=00;35:*.tif=00;35:'
MACHTYPE=i686-redhat-linux-gnu
MAIL=/var/spool/mail/root
OPTERR=1
OPTIND=1
OSTYPE=linux-gnu
PATH=/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/sbin:/opt/FriendlyARM/toolschain/4.4.3/bin:/root/bin
POSIXLY_CORRECT=y
PPID=10065
PS4='+ '
PWD=/usr/c
SHELL=/bin/bash
SHELLOPTS=braceexpand:hashall:interactive-comments:posix
SHLVL=2
SSH_ASKPASS=/usr/libexec/openssh/gnome-ssh-askpass
TERM=xterm
UID=0
USER=root
XAUTHORITY=/root/.xauthj4RAgs
_=./source
the child process pid[i] = 10102
[root@yff c]#

最后的这个进程是defunct进程: the child process pid[i] = 10102



------解决方案--------------------
请使用while(((pid = wait()) == -1 && errno == EINTR) || pid > 0)来回收干净所有的子进程。