gpt4 book ai didi

c - 父子同步与 system-v 信号量

转载 作者:太空宇宙 更新时间:2023-11-04 04:28:02 27 4
gpt4 key购买 nike

我有一个函数,可以循环打印一个字符一个字符的内容。我想要做的是同步父进程和子进程,以便每个进程打印一行而不会受到其他干扰。我正在尝试用信号量来做到这一点。

这是我的代码:

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("hello\n");
semop(sem, &u, 1);
}



} else {
for (i=0;i<10;i++){
semop(sem, &d, 1);
print_char_by_char("world\n");
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: for some operation the value of sem_num is less than 0 or reater than or equal to the number of semaphores in the set.

然后,在不知道你的print_char_by_char 函数如何的情况下,我们无法知道你打印乱码的原因(记住printf 和其他是缓冲的,所以你应该使用fflush next,或者直接用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, "hello\n", 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, "world\n", 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 信号量

关于c - 父子同步与 system-v 信号量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39531816/

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