1
#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();
    }
}

如果我将上述代码作为 ac 代码运行,则 write_file() 函数在 update_file() 函数之后调用,而如果我将相同的代码作为 c++ 代码运行,则执行顺序是相反的……为什么会这样??

4

1 回答 1

1

只是一些建议,但在我看来这可能是由多种因素引起的:

  1. wait() 调用应该采用指针参数(可以为 NULL)。编译器应该已经捕捉到了这一点,但是您必须在允许您的语法的地方选择另一个定义。您还缺少 sys/wait.h 的包含。这可能就是编译器没有像我预期的那样抱怨的原因。

  2. 根据您的机器/操作系统配置,fork 的进程可能要等到父进程产生后才能运行。假设您正在调用的“wait()”没有按照我们预期的方式工作,那么父级可能会在子级运行之前完全执行。

不幸的是,我无法复制相同的时间行为。但是,当我为这两种情况(C 和 C++)中的每一种生成汇编文件时,我注意到 C++ 版本缺少“等待”系统调用,但 C 版本与我预期的一样。对我来说,这表明在 C++ 头文件中的某个地方,这个没有参数的特殊版本被 #defined 出代码。这种差异可能是您所看到的行为背后的原因。

简而言之......添加#include,并将您的等待调用更改为“wait(0)”

于 2013-04-11T00:23:54.480 回答