gpt4 book ai didi

c - 命名管道 C 问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:26:18 25 4
gpt4 key购买 nike

我有这个 C 代码:

   #define BUFSIZE 256
int main ( int argc, char *argv[])
{
int fdIn;
int fdOut;


if( argc != 3)
{
perror("Error argument");
exit(1);
}
printf("Input Pipe\n");
if( (fdIn = open(argv[1], O_RDONLY ) )<0)
{
perror("Error opening input pipe");
exit(1);
}
printf("Output Pipe\n");
if( (fdOut = open(argv[2], O_WRONLY ) )<0)
{
perror("Error opening output pipe");
exit(1);
}

int c = 2;
printf("Start cicle\n");
while(c--)
{
char var1[BUFSIZE];
char var2[BUFSIZE];
char string[100];

memset(var1, 0, sizeof(var1));
memset(var2, 0, sizeof(var2));
memset(string, 0, sizeof(string));


if( readLine(fdIn, var1, sizeof(var1)) == 0)
{
printf("exit \n");
exit(0);
}

if( readLine(fdIn, var2, sizeof(var2)) == 0)
{
printf("exit \n");
exit(0);
}



if( atoi(var2) != 0){
if( atoi(var1) == 0 || (atoi(var1) % atoi(var2)) == 0 )
sprintf(string,"ok\n");
else
sprintf(string,"no\n");

}

printf("%s", string);
writeLine(fdOut, string, strlen(string));
}
close(fdOut);
close(fdIn);
exit(0);
}

代码中的函数:

int readLine( int fd, char* str, int bufferSize)
{
return readToDel(fd, '\n', str, bufferSize);
}

int readToDel( int fd, char delimiter, char* str, int bufferSize)
{
int n;
int byteLetti =0;
int index=0;


do /* Read characters until NULL or end-of-input */
{

if( (n = read (fd, str+index, 1)) < 0)
{
perror("Error descriptor\n");
exit(1);
}
byteLetti+=n;


}
while (n > 0 && *(str+index++) != delimiter && index < bufferSize);


return byteLetti; /* Return false if end-of-input */
}
int writeLine(int fd, char* buffer, int bufferSize)
{
if( write (fd, buffer, bufferSize) < 0)
{
perror("Error");
exit(1);
}
}

我的问题是如何使用这些管道,我会解释:

我有 2 个输入管道(输入的程序是 2 个绝对管道的路径),其中一个是输入管道,另一个是输出管道。在输入管道中有一些数据(特别是两个数字),在详细说明之后,我必须在输出管道中写上“ok”或“no”。出于这个原因,通过终端,我做了 echo "4\n2\n"> input 所以我在输入的管道中写入了两个数字。然后我这样执行程序:

./program inputPipeAbsolutePath outputPipeAbsolutePath

但程序在 printf("Output Pipe\n"); 行上阻塞,在开始的第三个 if 语句之前,我不知道为什么。怎么了?

我在 Mac 上测试过

更新没有人可以帮助我吗?

最佳答案

the program blocks on the opening of the output pipe and I do not know how to behave.

该程序的行为与记录的一样;见man fifo :

       Normally, opening the FIFO blocks until the other end is opened also.

因此,您的一个选择是启动一个从您的输出管道读取的程序(例如cat);然后您的程序将继续。
另一种选择是使用 O_RDWR 而不是 O_WRONLY:

       Under Linux, opening a FIFO for read and write will succeed both in       blocking and nonblocking mode.  POSIX leaves this behavior undefined.       This can be used to open a FIFO for writing while there are no       readers available.

关于c - 命名管道 C 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34453150/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com