我有以下代码,我正在使用该函数mkfifo
创建一个 Fifo,但问题是当我运行程序时,我得到 printf 说“创建 fifo 时出错”。会是什么呢?这是代码:
//gcc Exam.c -o p
//./p 5 /home/directoryFile.c
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/wait.h>
int main(int argc, char *argv[])
{
int studentId, children = 0, j, i, childNumber[15], fdFile, fdread, fdFifo, fdOpenFifo;
float bytesToRead;
char directory[50];
char *buffer = malloc(256), *textToSend = malloc(256), *buffer2 = malloc(256);
char childFifo[16];
system("clear");
if(argc-1 < 1)
{
printf("\nSome arguments are missing\n");
return EXIT_FAILURE;
}
studentId = atoi(argv[1]);
strcpy(directory,argv[2]);
if((studentId%2) == 0)
{
children = 15;
}
else
{
if((studentId%3) == 0)
{
children = 10;
}
else
{
if((studentId%5) == 0)
{
children = 7;
}
else
{
printf("\nThe studentId is invalid \n");
return EXIT_FAILURE;
}
}
}
struct stat fileInfo;
stat(argv[2],&fileInfo);
bytesToRead = fileInfo.st_size / children;
printf("Children: %d\n",children);
printf("File size: %lld\n",(long long int) fileInfo.st_size);
printf("Bytes: %.2f\n",bytesToRead);
fdFile = open(directory,O_RDONLY);
if(fdFile == -1)
{
printf("\nError opening file\n");
return EXIT_FAILURE;
}
for(i=0;i<children;i++)
{
sprintf(childFifo,"Child_%d",i);
fdFifo = mkfifo(childFifo,0777);
if(fdFifo == -1)
{
printf("\nError creating the fifo\n");
return EXIT_FAILURE;
}
childNumber[i] = fork();
if(childNumber[i] == -1)
{
printf("\nError creating the child\n");
return EXIT_FAILURE;
}
if(childNumber[i] == 0)
{
fdOpenFifo = open(childFifo,O_WRONLY);
if(fdOpenFifo == -1)
{
printf("\nError opening the fifo\n");
return EXIT_FAILURE;
}
fdread = read(fdFile,buffer,bytesToRead);
if(fdread == -1)
{
printf("\nError reading the file\n");
return EXIT_FAILURE;
}
//printf("%s",buffer);
//printf("\n\n------------------------\n\n");
write(fdOpenFifo,&buffer,sizeof(char));
//sprintf(textToSend,"%s%s",textToSend,buffer);
return EXIT_SUCCESS;
}
else
{
sleep(1);
read(fdOpenFifo,&buffer2,sizeof(char));
printf("\nI show the content of the file: %s\n",buffer2);
//waitpid(childNumber[i],NULL,WNOHANG);
close(fdOpenFifo);
}
}
//printf("\nI show the content of the file: %s\n",textToSend);
close(fdFile);
for(j=0;j<children;j++)
{
wait(NULL);
}
return EXIT_SUCCESS;
}
这是输出:./p 5 /home/directoryFile.c
Children: 7
File size: 267
Bytes: 38.00
Error creating the fifo