gpt4 book ai didi

c - 如何在父子之间传递字符串?

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

#include<stdio.h>
#include<stdlib.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/types.h>
#include<string.h>
#include<sys/stat.h>
#define SIZE 100

void main()
{
int shmid,status;
pid_t pid;
int i;
char *a,*b,d[100];
shmid=shmget(IPC_PRIVATE,SIZE,S_IRUSR | S_IWUSR);
pid=fork();


if(pid==0)
{
b=(char *) shmat(shmid,NULL,0);
printf("enter");
printf("%c",*b);
shmdt(b);
}
else
{
a=(char *) shmat(shmid,NULL,0);
printf("enter a string");
scanf("%s",&d);
strcpy(a,d);
shmdt(a);
}
}

我试图将一个字符串从父进程传递到子进程。但在将值扫描到“d”之前,程序会切换到子进程。我应该如何纠正这个逻辑错误?我应该如何将这个字符串“d”传递给子进程?

最佳答案

调用 fork 后,您永远不知道哪个进程会先执行。您必须简单地断言您的代码可以正确处理进程间通信,无论现在发生什么。

您可以使用 pipe(2)或共享内存在同一主机上的不同进程之间传递数据。

#include <unistd.h>

int pipe(int pipefd[2]);

但是您也可以在调用 fork 之前将数据读入全局变量。 Fork 将在新进程中创建全局数据的副本。


使用 shmget 共享内存 example .

关于c - 如何在父子之间传递字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32800667/

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