问一个简单的进程同步/互斥的有关问题 [C 语言]
问一个简单的进程同步/互斥的问题 [C 语言]
目的很简单:建立一个子进程,生成一个整数并放在 buffer 中,然后在父进程中读出 buffer 中的值并输出,我按照我的想法写了一段 C 语言代码,但输出结果是 0。该例子使用了信号量进行互斥。代码如下:
请问该怎么修改?
------解决方案--------------------
.........................................
父子进程各对buffer有一份拷贝,两个是不同的;
------解决方案--------------------
目的很简单:建立一个子进程,生成一个整数并放在 buffer 中,然后在父进程中读出 buffer 中的值并输出,我按照我的想法写了一段 C 语言代码,但输出结果是 0。该例子使用了信号量进行互斥。代码如下:
- C/C++ code
#include <fcntl.h> #include <unistd.h> #include <semaphore.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> int main(void) { int *buff = (int *)malloc(sizeof(int)); pid_t pid; sem_t *sem_empty = sem_open("empty", O_CREAT, 0644, 1), *sem_full = sem_open("full", O_CREAT, 0644, 0); pid = fork(); switch (pid) { case (-1): { printf("Failure!\n"); break; } case (0): { sem_wait(sem_empty); *buff = 1234; sem_post(sem_full); break; } default: { sem_wait(sem_full); printf("%d\n", *buff); sem_post(sem_empty); break; } } wait(NULL); sem_unlink("empty"); sem_unlink("full"); return (0); }
请问该怎么修改?
------解决方案--------------------
.........................................
父子进程各对buffer有一份拷贝,两个是不同的;
------解决方案--------------------