gpt4 book ai didi

c - 为什么这个命名管道不打印发送的行?

转载 作者:太空宇宙 更新时间:2023-11-04 03:06:31 26 4
gpt4 key购买 nike

以下服务器在像这样运行时会创建一个命名管道:

./serverprogram -p nameofthepipe -t 99

t后面的optarg表示要创建的线程数(这里没有做)。

无论如何,这里的管道不起作用:

/* Open the first named pipe for reading */
int rdfd = open(pipeName, O_RDONLY);

/* Read from the first pipe */
int numread = read(rdfd, command_and_pid, 280);


printf("what's being read is %s \n", command_and_pid); // not printing!!1!

为什么?

服务器程序:

#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>



int main (int argc, char * argv[])
{

char pipeName[30];
int numThreads;

char command_and_pid[280];


int opcion;
if (argc < 2) {
printf ("ERROR: Missing arguments\n");//
exit(1);
}
opterr = 0;




while ((opcion = getopt (argc, argv, "p:t:w")) != -1)
{
switch (opcion) {

case 'p': // -p indica el nombre del pipe
printf("The name of the pipe is: %s\n",optarg);
strcpy(pipeName, optarg);

break;

case 't'://-t indica los hilos
printf("The number of threads is: %s\n",optarg);
numThreads= atoi(optarg);

break;

case '?':
fprintf(stderr,"no reconozco esa opcion\n");
break;
}
}





int ret_val = mkfifo(pipeName, 0666);

if ((ret_val == -1) && (errno != EEXIST)) {
perror("Error creating the named pipe");
exit (0);
}


/* Open the first named pipe for reading */
int rdfd = open(pipeName, O_RDONLY);

/* Read from the first pipe */
int numread = read(rdfd, command_and_pid, 280);


printf("what's being read is %s \n", command_and_pid); // not printing!!1!


close(rdfd);


return 0;
}

客户端程序:

#include <unistd.h>
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>





int main (int argc, char * argv[])
{



char pipeName[30];

printf("write the name of the pipe used to write to the server \n");

fgets(pipeName,30, stdin);

/* Open the first named pipe for writing */
int wrfd = open(pipeName, O_WRONLY);


printf("write the name of the command you want to execute \n");

char command_and_pid[280];
char command[250];


fgets(command,250, stdin);
puts(command); //quitar

strcpy(command_and_pid,command);
strcat(command_and_pid," ");


int pipeIntId;

char pidstring [30];

int pid= getpid();

sprintf(pidstring,"%d", pid);

strcat(command_and_pid,pidstring);

int written;

written=write(pipeIntId,command_and_pid,280);
//write to the pipe
// send the command and pid


close(pipeIntId); // close write pipe


return 0;
}

最佳答案

在客户端中,fgets 将换行符保留在行尾,因此您需要在打开文件之前去除它。

此外,在给定的代码中,您正在打开 wrfd 但写入未初始化的 pipeIntId(尽管您可能正在从此处的函数中提取一些内容) .

关于c - 为什么这个命名管道不打印发送的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4310333/

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