2013-04-09 100 views
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++代码,订单之后称为的执行是反向的...为什么这样呢?顺序派生进程

+0

这是否发生总是? – 2013-04-09 19:43:03

+0

@ bash d:是的..它发生在我写到现在为止的所有程序中。 – 2013-04-10 15:48:02

回答

1

只是一些建议,但它看起来对我来说,它可以通过一个事物的组合引起:

  1. ()调用应该采取一个指针参数的等待(可以 为NULL) 。编译器应该已经发现了这个问题,但是你必须在另一个定义的地方选择 来允许你的语法。你是 也缺少一个包含sys/wait.h。这可能是为什么 编译器没有像我期望的那样抱怨。

  2. 根据您的机器/操作系统配置,fork'd进程可能会在父进程退出之前运行 。假设您所调用的“wait()” 未按照我们期望的方式工作,则在子节点 运行之前,父节点可能完全执行为 。

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

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