我寫了一個簡單的代碼,其中一個進程傳遞一個結構到另一個進程,父進程寫入數據,但子進程是不能夠訪問它。我用fork()
系統調用來創建兩個進程。但我在這裏有問題,我調用兩次的父進程,當我運行程序時,子進程也被調用兩次。任何人都可以讓我知道我在做什麼錯誤。傳遞一個結構通過FIFO
#include <stdlib.h>
#include <signal.h>
#include <stdio.h>
#include <errno.h>
#include <sys/errno.h>
#include <fcntl.h>
#include <string.h>
#define MAX_LINE_LEN 100
#define FIFO_NAME "my_fifo"
typedef struct student_info {
char *name;
int age;
char *sex;
}student;
int w_byte_parent = 0, r_byte_parent = 0;
int w_byte_child = 0, r_byte_child = 0;
void do_child() {
int fifo;
char buffer[MAX_LINE_LEN];
int i = 0;
student child;
printf("Child opening FIFO \n");
if((fifo = open(FIFO_NAME, O_RDWR)) < 0) {
perror("open in child failed");
exit(EXIT_FAILURE);
}
printf("Child reading from FIFO \n");
r_byte_child = read(fifo, child, sizeof(student));
if(r_byte_child < 0)
printf("Read failed by child process\n");
printf("%d Bytes read by child process\n", r_byte_child);
}
int main(int argc, char **argv) {
int fifo;
char buffer[MAX_LINE_LEN];
int ch = 0, i = 0;
/*
** Create a FIFO
*/
/* Parent creating FIFO */
if((mkfifo(FIFO_NAME, 0666)) < 0) {
if(errno != EEXIST) {
perror("mkfifo");
exit(EXIT_FAILURE);
}
}
/*
** Create other process
*/
switch(fork()) {
case -1:
perror("fork()");
exit(EXIT_FAILURE);
case 0: /* Child Process */
do_child();
break;
default:/* Parent Process */
break;
}
/* Pass a structure to FIFO */
student *info;
info = (student *)malloc(sizeof (student)) ;
info->name = (char *)calloc(sizeof(char), 10);
strcpy(info->name, "jack");
info->age = 27;
info->sex = (char *)calloc(sizeof(char), 10);
strcpy(info->sex , "Male");
/* Parent Opening FIFO */
printf("parent opening FIFO \n");
if((fifo = open(FIFO_NAME, O_RDWR)) < 0) {
perror("open in parent failed");
exit(EXIT_FAILURE);
}
/*
** Write some thing into FIFO so child can read it
*/
printf("parent writing to FIFO \n");
w_byte_parent = write(fifo, info, sizeof(struct student_info));
if(w_byte_parent < 0)
printf("Nothing was written to FIFO by parent\n");
printf("Wrote %d bytes to FIFO\n",w_byte_parent);
}
父節點和子節點都退出交換機(fork())。那是你想要的嗎? –