qq_43066253
丶xiaoHai
采纳率44.3%
2020-05-24 09:27 阅读 186

关于linux下c语言进程控制的问题

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/sem.h>
#include <sys/ipc.h>
#include <errno.h>
#include <fcntl.h>
#include <semaphore.h>
#include <signal.h>
#define FIFO "../myfifo"
int waitsem(int sem_id) {
    //把信号量操作封装到函数中,提高代码可读性
    struct sembuf sem_b;
   sem_b.sem_num = 0;
   sem_b.sem_op = -1;
   sem_b.sem_flg = SEM_UNDO;
   if(semop(sem_id,&sem_b,1) == -1){
        fprintf(stderr, "P failed\n");
        return 0;        
    }//if
   return 1;
}
int signalsem(int sem_id){
    struct sembuf sem_b;
    sem_b.sem_num = 0;
    sem_b.sem_op =  1;
    sem_b.sem_flg = SEM_UNDO;
    if(semop(sem_id,&sem_b,1) == -1){
        fprintf(stderr, "V failed\n");
        return 0;
    }//if
   return 1;
}
int main(int argc,int argv[]){
    pid_t pid1,pid2;
    int fd,flag;
    flag = semget(IPC_PRIVATE,1,0666|IPC_CREAT);
    semctl(flag,0,SETVAL,1);
    fd=open(FIFO,O_RDONLY,0); 
    if (fd<0) {
        printf("no such namedpipe file !!\n");
        exit(1); 
    }
    pid1 = fork();
    pid2 = fork();
    if(pid1>0&&pid2>0){
        // father thread
        waitsem(flag);
        char msg[20];
        printf("father: Please input the message: ");
        scanf("%s",msg);
        write(fd,msg,strlen(msg));
        printf("father:Write success!\n");
        signalsem(flag);
    }else if(pid1==0&&pid2>0){
        waitsem(flag);
        char msg[20];
        printf("P1: Please input the message: ");
        scanf("%s",msg);
        write(fd,msg,strlen(msg));
        printf("P1:Write success!\n");
        signalsem(flag);
    }else if(pid1>0&&pid2==0){
        waitsem(flag);
        char msg[20];
        printf("P2:Please input the message: ");
        scanf("%s",msg);
        write(fd,msg,strlen(msg));
        printf("P2:Write success!\n");
        signalsem(flag);
    }else{
        waitsem(flag);
        char msg[20];
        printf("P3:Please input the message: ");
        scanf("%s",msg);
        write(fd,msg,strlen(msg));
        printf("P3:Write success!\n");
        signalsem(flag);
    }
    printf("Write finish!\n");
    return 0;
}

请大佬们看一下上面的代码片,为什么任何一条打印语句都会不执行呢?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

相关推荐