我想通过命名管道发送分配的字符串,而不是简单的字符数组。
我得到了以下代码:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>
int main()
{
int pid, fd;
fd = mkfifo("fifo.ftc", S_IRUSR | S_IWUSR);
pid = fork();
char* send, * recieve;
if(pid == 0) {
recieve = malloc(100);
fd = open("fifo.ftc", O_RDONLY);
read(fd, recieve, sizeof(recieve));
close(fd);
printf("%s\n", recieve);
send = malloc(100);
send = "This text was sent by child!";
fd = open("fifo.ftc", O_WRONLY);
write(fd, send, sizeof(send));
close(fd);
free(recieve);
free(send);
} else if(pid > 0) {
send = malloc(100);
send = "This text was sent by parent!";
fd = open("fifo.ftc", O_WRONLY);
write(fd, send, sizeof(send));
close(fd);
recieve = malloc(100);
fd = open("fifo.ftc", O_RDONLY);
read(fd, recieve, sizeof(recieve));
close(fd);
printf("%s\n", recieve);
unlink("fifo.ftc");
free(send);
free(recieve);
}
}
作为输出,我总是收到:
This tex
This tex
看起来它并没有打印出整个字符串。如何接收父子的完整消息?
最佳答案
您的代码中有多个错误。
你必须记住 read和 write不保证他们会有效地读取或写入您告诉他们的字节数。
来自 Linux write 手册页:
Synopsis
#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);
Description
write() writes up to count bytes from the buffer pointed buf to the file referred to by the file descriptor fd. The number of bytes written may be less than count if, for example, there is insufficient space on the underlying physical medium, or the RLIMIT_FSIZE resource limit is encountered (see setrlimit(2)), or the call was interrupted by a signal handler after having written less than count bytes. (See also pipe(7).)
它们返回读取或写入的字节数,因此您必须将它们的返回值存储在变量中并相应地进行处理。您通常会将它们包装在一个循环中,保留一个计数器来累计读取/写入的字节数,并在达到原始缓冲区大小时或返回错误值时退出循环。
正如@wildplasser 在评论中提到的,您滥用了
sizeof
运算符。当你执行char *foo; sizeof foo;
,得到的大小不是foo
指向的字符串的大小,而是char指针类型的大小(64位架构8字节,32位4字节).您应该改用strlen(foo)
。
关于C通过命名管道发送分配的字符串 - linux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43893077/