【问题标题】:Process synchronization with C languageC语言进程同步
【发布时间】:2013-04-08 18:44:01
【问题描述】:

我尝试将牵引进程(子进程和父进程)与信号量同步,但我的尝试失败了。

C源代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>
#include <fcntl.h>
#include <sys/stat.h>


int compteur=0;
sem_t *sem;

int main()
{
        void *ret;
        sem = sem_open("/sem", O_CREAT, 0644, compteur);
        sem_init(sem, 0, 0);
        pid_t pid;
        pid=fork();
        switch (pid)
        {
            case -1:
                printf("Erreur: echec du fork()\n");
                exit(1);
                break;
            case 0:
                /* PROCESSUS FILS */
                printf("Processus fils : pid = %d\n", getpid() );
                sem_post(sem);
                break;
            default:
                sem_wait(sem);
                /* PROCESSUS PERE */
                printf("Ici le pere%d: le fils a un pid=%d\n",getpid(),pid);
                printf("Fin du pere.\n");
    }   
}

我认为问题在于信号量在子进程中不可见。我该如何解决这个问题?

【问题讨论】:

  • 可能重复,但请先查看here
  • 可能你已经解决了,但是这里的解决方案是使用sharedmemory来共享信号量:当你创建一个子进程时,父进程的变量是DUPLICATED的,不是共享的(就像在线程中一样),所以你在不同的信号量上调用 sem_post 和 sem_wait !否则,如果你使用一段共享内存来保存信号量并在不同的进程中使用它。我给你链接一个运行良好的程序:link

标签: c process synchronization fork semaphore


【解决方案1】:

您的sem_init 应该是:

sem_init(sem, 1, 0);  

也就是说,第二个参数应该不为零。
因为对于:

#include <semaphore.h>
int sem_init(sem_t *sem, int pshared, unsigned int value);

(来自man sem_init

If  pshared  has  the  value 0, then the semaphore is shared between the threads of a process...
If pshared is nonzero, then the semaphore is shared between processes...

【讨论】:

    【解决方案2】:

    0 是主进程,-1 是错误,任何大于 0 的值都是子进程。您必须有机会切换到 >0 才能获得孩子。

    【讨论】:

    • 但是当我在没有信号量的情况下执行它时,“默认”部分(>0)在部分(=0)之前开始,此外,pid 的显示也证实了这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    相关资源
    最近更新 更多