#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/sem.h>
#include<sys/ipc.h>
int sem_id;
void update_file(int number)
{
struct sembuf sem_op;
FILE* file;
printf("Inside Update Process\n");
/* wait on the semaphore, unless it's value is non-negative. */
sem_op.sem_num = 0;
sem_op.sem_op = -1; /* <-- Amount by which the value of the semaphore is to be decreased */
sem_op.sem_flg = 0;
semop(sem_id, &sem_op, 1);
/* we "locked" the semaphore, and are assured exclusive access to file. */
/* manipulate the file in some way. for example, write a number into it. */
file = fopen("file.txt", "a+");
if (file) {
fprintf(file, " \n%d\n", number);
fclose(file);
}
/* finally, signal the semaphore - increase its value by one. */
sem_op.sem_num = 0;
sem_op.sem_op = 1;
sem_op.sem_flg = 0;
semop( sem_id, &sem_op, 1);
}
void write_file(char* contents)
{
printf("Inside Write Process\n");
struct sembuf sem_op;
sem_op.sem_num = 0;
sem_op.sem_op = -1;
sem_op.sem_flg = 0;
semop( sem_id, &sem_op, 1);
FILE *file = fopen("file.txt","w");
if(file)
{
fprintf(file,contents);
fclose(file);
}
sem_op.sem_num = 0;
sem_op.sem_op = 1;
sem_op.sem_flg = 0;
semop( sem_id, &sem_op, 1);
}
int main()
{
//key_t key = ftok("file.txt",'E');
sem_id = semget( IPC_PRIVATE, 1, 0600 | IPC_CREAT);
/*here 100 is any arbit number to be assigned as the key of the
semaphore,1 is the number of semaphores in the semaphore set, */
if(sem_id == -1)
{
perror("main : semget");
exit(1);
}
int rc = semctl( sem_id, 0, SETVAL, 1);
pid_t u = fork();
if(u == 0)
{
update_file(100);
exit(0);
}
else
{
wait();
}
pid_t w = fork();
if(w == 0)
{
write_file("Hello!!");
exit(0);
}
else
{
wait();
}
}
如果我将上面的代码作为c代码运行,则在update_file()函数之后调用write_file()函数 然而,如果我运行与c ++代码相同的代码,执行的顺序是相反的......为什么会这样?
答案 0 :(得分:1)
只是一些建议,但在我看来,它可能是由一系列事情引起的:
wait()调用应该采用指针参数(可以 是NULL)。编译器应该抓住这个,但你必须选择 某个允许你的语法的另一个定义。你是 还缺少sys / wait.h的include。这可能就是为什么 编译器并没有像我期望的那样抱怨。
根据您的机器/操作系统配置,fork'd进程可能会 在父母屈服之后才能运行。假设“等待()” 你打电话的方式并不像我们期望的那样,就是这样 父母可以在孩子面前完全执行 跑去跑。
不幸的是,我无法复制相同的时间行为。但是,当我为这两种情况(C&amp; C ++)中的每一种生成汇编文件时,我注意到C ++版本缺少“等待”系统调用,但C版本正如我所料。对我来说,这表明在C ++标题中的某个地方,这个没有参数的特殊版本正在代码中被#defined定义。这种差异可能是您所看到的行为背后的原因。
简而言之......添加#include,并将等待调用更改为“wait(0)”