我现在不能给代码,因为我现在在脑子里想这个主意,在网上乱搞。
我已经学习了进程间通信和使用共享内存在进程之间共享数据(特别是结构)。
但是,在另一个.c文件中保存的程序上使用fork()和execv(…)之后,我对如何与进程共享数据感到困惑。
如果我们将信号量键作为参数提供给另一个程序(成为子进程),我们是否能够使用semget访问共享内存?

最佳答案

第一件事。
取决于实现,单个或多个源文件,.c在您的情况下可以构成单个可执行文件。一个可执行文件运行一个进程。如果源代码中完成了fork(),则创建子进程。所以,你的
…不同.c文件之间的进程间通信
不必是两个.c文件,不管它们是作为单个项目还是两个不同的项目编译的。
简单地说,您有两个不同的源文件,其中一个应该创建一个共享内存。

#define SHMSPACE    35
char *shm, *str;
key_t key = 1234;

//Create a memory segment to be shared
if ((shmid = shmget(key, SHMSPACE, IPC_CREAT | 0666)) < 0)
{
    perror("shmget failed");
    exit(1);
}

//Attach the segment to memory space.
if ((shm = shmat(shmid, NULL, 0)) == (char *) -1)
{
    perror("shmat failed");
    exit(1);
}

//Write something like A to Z in the shared memory for other process to read
str = shm;
for (c = 'A'; c <= 'Z'; c++) //c is declared as an int somewhere above.
    *str++ = c;
*str = NULL;

您的其他来源应该是:
#define SHMSPACE    35
char *shm, *str;
key_t key = 1234;

//Get the shared memory segment
if ((shmid = shmget(key, SHMSPACE, 0666)) < 0)
{
    perror("shmget failed");
    exit(1);
}

//Attach the segment to our data space.
if ((shm = shmat(shmid, NULL, 0)) == (char *) -1)
{
    perror("shmat");
    exit(1);
}

//Read what other process has put in the memory.
for (str = shm; *str != NULL; s++)
    putchar(*str);

关于c - 不同.c文件之间的IPC进程间通信,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30524004/

10-11 23:08
查看更多