【发布时间】:2017-04-03 05:31:40
【问题描述】:
我正在尝试制作一个从 0 计数到 C 命令行中输入的任何数字的程序。在这个程序中,必须有两个 fork() 调用,总共有 3 个进程。然后我必须使用至少 1 个信号量来确保进程按数字顺序运行,每个进程负责不同的 n % 3。
我遇到的问题是,尽管我使用了信号量,但程序似乎经常出现故障。我目前正在使用一个门式系统,其中每个进程都会强制它自己指定的信号量等待,一旦完成,sem_post 应该运行下一个进程的信号量。我知道这不是最漂亮或最合乎逻辑的有效方式,但在我遇到同样问题的前两次不同尝试之后,我很确定它会奏效。
如果有人能给我任何关于我哪里出错的建议,我将非常感激。
我的代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/types.h>
#include <unistd.h>
#include <semaphore.h>
#include <fcntl.h>
#define SEM_NAME1 "/sem1.mutex"
#define SEM_NAME2 "/sem2.mutex"
#define SEM_NAME3 "/sem3.mutex"
int main(int argc, char *argv[]) {
if(argc <= 1){
printf("No arguments were provided so there is no number to count to");
return 1;
}
// Create the 3 semaphores needed
sem_t *sem1;
sem_t *sem2;
sem_t *sem3;
//initialize to 0
sem1 = sem_open(SEM_NAME1, O_CREAT, O_RDWR, 0);
if (sem1==SEM_FAILED) {
printf("%s sem_open failed!", SEM_NAME1);
return (-1);
}
//initialize to 1
sem2 = sem_open(SEM_NAME2, O_CREAT, O_RDWR, 1);
if (sem2==SEM_FAILED) {
printf("%s sem_open failed!", SEM_NAME2);
return (-1);
}
//initialize to 1
sem3 = sem_open(SEM_NAME3, O_CREAT, O_RDWR, 1);
if (sem3==SEM_FAILED) {
printf("%s sem_open failed!", SEM_NAME3);
return (-1);
}
pid_t pid;
pid_t pid2;
pid = fork();
if(pid == 0){
pid2 = fork();
}
// Shared fork variables
int counter = 0;
int ranOnce = 0;
int max_num = atoi(argv[1]);
while(counter <= max_num){
if(pid > 0){
printf("%d",getpid());
if(ranOnce == 0){
counter += 1;
ranOnce = 1;
}
sem_wait(sem2);
printf(" %d \n", counter);
counter += 3;
sem_post(sem3);
}
else if(pid2 == 0){
printf("%d",getpid());
if(ranOnce == 0){
counter += 0;
ranOnce = 1;
}
sem_wait(sem1);
printf(" %d \n", counter);
counter += 3;
sem_post(sem2);
}
else{
printf("%d",getpid());
if(ranOnce == 0){
counter += 2;
ranOnce = 1;
}
sem_wait(sem3);
printf(" %d \n", counter);
counter += 3;
sem_post(sem1);
}
}
//sem_unlink(SEM_NAME1);
//sem_unlink(SEM_NAME2);
//sem_unlink(SEM_NAME3);
return 0;
}
【问题讨论】: