gpt4 book ai didi

c - 在c中通过命名管道传递数组

转载 作者:太空宇宙 更新时间:2023-11-04 02:49:00 25 4
gpt4 key购买 nike

我正在尝试将 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;
}

你能帮忙吗?提前致谢!

最佳答案

您理解的问题是命名管道就像文件或流一样,因此您可以将字节写入其中。

当你有一个指针数组(或多维数组)时,指针实际上会指向内存中的其他地方(数组之外),因此接收应用程序将只遵循这些指针并使用它们中位于该地址的任何内容地址空间(不同于发送方的地址空间)。

因此,您不能只是将数组复制到您的管道/文件/其他任何东西中,而是必须提取所有数据(按照指针)并单独写入。

此外,sizeof(total) 将始终是 sizeof(int)(因此可能是 4 或 8),无论 total.

关于c - 在c中通过命名管道传递数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24097433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com