C -父子同步与系统v信号量



我有一个函数,在循环中逐字符打印一些东西。我要做的是同步父进程和子进程,以便每个打印一行没有其他干扰。我正在尝试用信号量来做这件事。

这是我的代码:

int main() {   
  int i, sem;   
  struct sembuf u   = {0, 1, 0};   
  struct sembuf d = {0 -1, 0};   
  sem = semget(IPC_PRIVATE, 1, 0600);   
  semctl(sem, 0, SETVAL, 1);
  if (!fork())   {
      for (i=0;i<10;i++){
          semop(sem, &d, 1)) < 0)
          print_char_by_char("hellon");
          semop(sem, &u, 1);
      }

  } else {
      for (i=0;i<10;i++){
          semop(sem, &d, 1);
          print_char_by_char("worldn");
          semop(sem, &u, 1);
      }

      semctl(sem, 0, IPC_RMID);
  }
  return 0; 
}

所以这是不工作,打印是乱码,我真的不知道为什么。同样,如果我像这样在semop上加上一个复选框:

if((x = semop(sem, &down, 1)) < 0)
    perror("semop");

我得到semop: File too large

根据man semop

EFBIG:对于某些操作,sem_num的值小于0或大于或等于集合中信号量的个数。

那么,不知道你的print_char_by_char函数如何,我们不知道为什么你得到乱码打印(记住printf和其他是缓冲的,所以你应该使用fflush接下来,或者直接使用write代替。

顺便说一下,我试着执行你的代码(我在下面写的),我没有任何问题(因为你没有指定你期望的输出),如果我删除
semctl(sem, 0, IPC_RMID);

可能你放错了位置(应该放在return之前,否则我猜第一个完成的人将删除信号量集)

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/sem.h>
void error_handler(const char *msg)
{
    perror(msg);
    exit(EXIT_FAILURE);
}
int main(int argc, const char **argv)
{
    if (argc != 1)
    {
        fprintf(stderr, "Usage: %s <no arguments>n", argv[0]);
        return EXIT_FAILURE;
    }
    int i, sem;
    struct sembuf u = {0, 1, 0};
    struct sembuf d = {0, -1, 0};
    sem = semget(IPC_PRIVATE, 1, 0600);
    semctl(sem, 0, SETVAL, 1);
    if (!fork())
    {
        for (i = 0; i < 10; i++)
        {
            if (semop(sem, &d, 1) == -1)
                error_handler("main | semop [d - father]n");
            if (write(STDOUT_FILENO, "hellon", 7) == -1)
                error_handler("main | write [hello]n");
            if (semop(sem, &u, 1) == -1)
                error_handler("main | semop [u - father]n");
        }
    } else {
        for (i = 0; i < 10; i++)
        {
            if (semop(sem, &d, 1) == -1)
                error_handler("main | semop [d - child]n");
            if (write(STDOUT_FILENO, "worldn", 7) == -1)
                error_handler("main | write [world]n");
            if (semop(sem, &u, 1) == -1)
                error_handler("main | semop [u - child]n");
        }
        // semctl(sem, 0, IPC_RMID);
    }
    return EXIT_SUCCESS;
}

world
world
world
world
world
world
world
world
world
world
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello

相反,如果你想以父子关系同步两个进程(这听起来很奇怪…)我建议您使用共享内存和POSIX信号量

最新更新