Operating system 分叉进程的执行顺序 #包括 #包括 #包括 #包括 #包括 int sem_id; 无效更新_文件(整数) { 结构sembuf sem_op; 文件*文件; printf(“内部更新过程\n”); /*等待信号量,除非它的值是非负的*/ sem_op.sem_num=0; sem_op.sem_op=-1;/*
只是一些建议,但在我看来,这可能是由多种因素共同造成的:Operating system 分叉进程的执行顺序 #包括 #包括 #包括 #包括 #包括 int sem_id; 无效更新_文件(整数) { 结构sembuf sem_op; 文件*文件; printf(“内部更新过程\n”); /*等待信号量,除非它的值是非负的*/ sem_op.sem_num=0; sem_op.sem_op=-1;/*,operating-system,Operating System,只是一些建议,但在我看来,这可能是由多种因素共同造成的: wait()调用应该采用指针参数(可以 编译器应该已经捕捉到这一点,但您必须正在拾取 在允许语法的地方创建另一个定义 还缺少sys/wait.h的include。这可能是 编译器并没有像我期望的那样抱怨 根据您的机器/操作系统配置,分叉进程可能会 直到父级生成后才能运行。假设“wait()” 你打电话的方式和我们期望的不一样,是的 父级可以在子级之前完全执行 开始跑步 遗憾的是,我不能复制相同的时间行为。但是,当我为两个案例(C&C++)
简言之,添加“包含”,并将您的等待呼叫更改为“等待(0)”只是一些建议,但在我看来,这可能是由多种因素共同造成的:
简而言之…添加#include,并将您的等待调用更改为“wait(0)”这种情况总是发生吗???@bash d:yeah..这种情况发生在我迄今为止编写的所有程序中…这种情况总是发生吗???@bash d:yeah..这种情况发生在我迄今为止编写的所有程序中。。。
#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();
}
}