在单个程序中通过fifo处理发送字符串

时间:2019-05-23 18:35:41

标签: process fifo mknod

我有这个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。

我想念什么?我只是想向父母发送一个字符串并在那里打印。

0 个答案:

没有答案