我有这个 fifo 示例,其中子进程向父进程发送一个整数。我希望它改为发送一个字符串,但它不起作用。
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
void errexit(char *errMsg){
printf("\n About to exit: %s", errMsg);
fflush(stdout);
exit(1);
}
int main()
{
char ret;
pid_t pid;
char value;
char fifoName[]="/tmp/testfifo";
char errMsg[1000];
char input_string[30];
scanf("%s", input_string);
FILE *cfp;
FILE *pfp;
ret = mknod(fifoName, S_IFIFO | 0600, 0);
/* 0600 gives read, write permissions to user and none to group and world */
if(ret < 0){
sprintf(errMsg,"Unable to create fifo: %s",fifoName);
errexit(errMsg);
}
pid=fork();
if(pid == 0){
/* child -- open the named pipe and write an integer to it */
cfp = fopen(fifoName,"w");
if(cfp == NULL)
errexit("Unable to open fifo for writing");
ret=fprintf(cfp,"%s",input_string);
fflush(cfp);
exit(0);
}
else{
/* parent - open the named pipe and read an integer from it */
pfp = fopen(fifoName,"r");
if(pfp == NULL)
errexit("Unable to open fifo for reading");
ret=fscanf(pfp,"%s",&value);
if(ret < 0)
errexit("Error reading from named pipe");
fclose(pfp);
printf("This is the parent. Received value %d from child on fifo \n", value);
unlink(fifoName); /* Delete the created fifo */
exit(0);
}
}
我在 'ret=fscanf(pfp,"%s", value);' 处收到错误,说 %s 需要 char 但 value 是 int 类型,即使它不是。它被声明为char。
我错过了什么?我只是想向父母发送一个字符串并在那里打印。