您的位置:首页 > 运维架构 > Linux

Linux wait 函数实参为指针时,没有预期结果,原因及其解决办法

2011-02-21 15:52 465 查看
在Linux/Unix



wait

一般用在,用户主程序调用

fork

产生一个新的进程后,等待子进程执行完毕。在标准的

Unix



wait

的头文件定义为:

#include <sys/wait.h>

pid_t wait(int *statloc);

在Linux

中,定义为:

/*come from /usr/include/sys/wait.h

  Wait for a child to die. When one does, put its status in *STAT_LOC ....

*/

extert  __pid_t  wait  (__WAIT_STATUS  __stat_loc);

也就是wait

的参数类型为

int 

的指针类型。

以下为一段程序。

#include<stdio.h>
#include<unistd.h>
#include<sys/wait.h>
int main(int argc, char *argv[])
{
pid_t pid1 =0;
pid_t child = 0;
int * s1;//@1
printf("main pid is %d,my ppid is %d/n",getpid(),getppid());
child = fork();
if(child <0)
{
printf("fork error/n");
exit(0);
}
if(child ==0)
{
printf("child pid is %d,my ppid is %d/n",getpid(),getppid());
sleep(1);
exit(0);
}
pid1 = wait(s1);//@2
printf("I will wait/n");
if(child == pid1)
{
printf("my pid is %d,waited pid is %d,s1= %d/n",getpid(),pid1,*s1);//@3
}
else
{
printf("no proecss waited/n");
}

return 0;
}


在Ubuntu10.4 

下的结果如下:

main pid is 1754,my ppid is 1265

child pid is 1755,my ppid is 1754

I will wait

no proecss waited

Wait返回的PID值为-1,也就是父进程,没有等待到子进程的结束。

 
把@1出的变量s1修改为:int s1。并在@2和@3中作相应的改动。

程序如下:

#include<stdio.h>
#include<unistd.h>
#include<sys/wait.h>
int main(int argc, char *argv[])
{
pid_t pid1 =0;
pid_t child = 0;
int  s1;//@1
printf("main pid is %d,my ppid is %d/n",getpid(),getppid());
child = fork();
if(child <0)
{
printf("fork error/n");
exit(0);
}
if(child ==0)
{
printf("child pid is %d,my ppid is %d/n",getpid(),getppid());
sleep(1);
exit(0);
}
pid1 = wait(&s1);//@2
printf("I will wait/n");
if(child == pid1)
{
printf("my pid is %d,waited pid is %d,s1= %d/n",getpid(),pid1,s1);//@3
}
else
{
printf("no proecss waited/n");
}

return 0;
}


同样在

在Ubuntu10.4 

下的结果如下:

main pid is 1774,my ppid is 1265

child pid is 1775,my ppid is 1774

I will wait

my pid is 1774,waited pid is 1775,s1= 0

 
这里父进程ID为1774,子进程ID为1775,并准确等待到了子进程的结束。

原因:

如果一个函数的参数为指针,比如int f(int *p),则p的实参可以定义为,int * p 或者是 int p;

如果是前者在调用时用f(p),如果是后者在调用时,利用f(&p);都可以。

在这里为什么不一样,大家说一说?

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  linux ubuntu unix
相关文章推荐