【发布时间】:2014-06-07 12:56:07
【问题描述】:
我正在尝试将 char ** 从父进程传递给子进程。当我尝试打印字符串时,我的程序没有错误地终止......只是终止了。这是我的代码:
我开始:
int main(int argc, char *argv[])
{
pid_t pid;
char **args;
int i;
if(argc < 3)
{
perror("Argc");
exit(1);
}
args = malloc(argc*sizeof(char *));
for(i=0; i<argc; i++)
{
if( i == (argc-1) )
{
args[i] = NULL;
break;
}
args[i] = malloc(strlen(argv[i+1])*sizeof(char));
strcpy(args[i], argv[i+1]);
printf("%s\n",args[i]);
}
if( server_exists() )
{
//pipes
}
else
{
pid = fork();
if(pid < 0)
{
perror("Fork");
exit(1);
}
else if( pid == 0 )
{
execl("./jobServer", "jobServer", NULL);
}
else if( pid > 0 )
{
for(i=0; i<argc-1; i++)
{
printf("%s\n",args[i]);
}
send_args(args, argc);
}
}
return 0;
}
一个有用的功能:
void send_args(char **args, int argc)
{
int fd, i;
char *myfifo = "myfifo";
int total = 0;
for(i=0; i<argc-1; i++)
{
total += (strlen(args[i])) + 1 ;
printf("%d %s\n",(strlen(args[i])), args[i]);
}
printf("asdf %d\n",total);
mkfifo(myfifo, 0666);
fd = open(myfifo, O_WRONLY);
write(fd, args, sizeof(total));
close(fd);
unlink(myfifo);
}
子进程(exec "jobServer"):
#define MAX_BUF 2048
int main(int argc, char *argv[])
{
int fd,i=0;
char *myfifo = "myfifo";
char *buf[MAX_BUF];
if( !server_exists() ) make_server(getpid());
fd = open(myfifo, O_RDONLY);
read(fd, buf, MAX_BUF);
//I can't print these
printf("%s\n",buf[0]);
printf("%s\n",buf[1]);
printf("%s\n",buf[2]);
close(fd);
return 0;
}
你能帮忙吗?提前致谢!
【问题讨论】:
标签: c pipe named-pipes