首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 操作系统 > UNIXLINUX >

施用posix_spawn创建多进程程序有点疑惑

2012-09-27 
使用posix_spawn创建多进程程序有点疑惑。我想使用posix_spawn或者posix_spawnp来创建一个子进程的例子,但

使用posix_spawn创建多进程程序有点疑惑。
我想使用posix_spawn或者posix_spawnp来创建一个子进程的例子,但是有点疑问。
创建总是成功的,但是,子进程的命令的输出总是看不到。不知道为什么。
代码如下:

C/C++ code
#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;}


[解决办法]
试试:
C/C++ code
#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有问题,具体修改的代码如下:
C/C++ code
#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;} 

热点排行