使用posix_spawn创建多进程程序有点疑惑。
我想使用posix_spawn或者posix_spawnp来创建一个子进程的例子,但是有点疑问。
创建总是成功的,但是,子进程的命令的输出总是看不到。不知道为什么。
代码如下:
#include <spawn.h>#include <stdio.h>#include <errno.h>#include <unistd.h>extern char **environ;int main(int argc, char * argv[]){ posix_spawnattr_t attr; posix_spawn_file_actions_t fact; pid_t pid; char args[][32]={"ls",NULL}; posix_spawnattr_init(&attr); posix_spawn_file_actions_init(&fact); if(posix_spawnp(&pid,"ls",&fact,&attr,(char**)args,(char**)environ)==0) { printf("child pid is %d",getpid()); return 0; } perror("posix_spawn"); printf("pid=%d\n",pid); return 0;}
#include <spawn.h>#include <stdio.h>#include <errno.h>#include <unistd.h>int main(int argc, char * argv[]){ pid_t pid; posix_spawnp(&pid, "ls", NULL, NULL, NULL, NULL); return 0;}
[解决办法]
是参数问题不假,但主要问题不是发生在posix_spawn这篇文章解释的范围。我也看了,也测试了,发现,是你构造的args有问题,具体修改的代码如下:
#include <spawn.h>#include <stdio.h>#include <errno.h>#include <unistd.h>#include <sys/types.h>#include <sys/wait.h>extern char **environ;int main(int argc, char * argv[]){ posix_spawnattr_t attr; posix_spawn_file_actions_t fact; pid_t pid; char cmd[]="ls"; char opt[]="-l"; char *args[3]; args[0]=cmd; args[1]=opt; args[2]=NULL; posix_spawnattr_init(&attr); posix_spawn_file_actions_init(&fact); posix_spawn(&pid,"/bin/ls",&fact,&attr,args,environ); perror("posix_spawn"); printf("pid=%d,child pid = %d\n",getpid(),pid); int stat=0; waitpid(pid,&stat,0); printf("stat is %d\n",stat); return 0;}