c - 使用 C 中的管道创建客户端和服务器时的奇怪行为

标签 c linux ubuntu client-server pipe

在这里,我尝试使用管道创建一个简单的客户端和服务器。我 fork 了一个进程,使子进程充当客户端,父进程充当服务器。下面是代码:

#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>

void errorMsg(char* msg)
{
    printf("\n%s\n", msg);
//  exit(0);
}

int main()
{
    int servfd[2];
    int clntfd[2];
    int chldpid;    

    if(pipe(servfd) < 0)
        errorMsg("Unable to create server pipe.!!");
    if(pipe(clntfd) < 0)
        errorMsg("Unable to create client pipe.!!!");
        
    if((chldpid = fork()) == 0)
    {
        char* txt = (char*) calloc(256, sizeof(char));
        close(servfd[1]);
        close(clntfd[0]);
        printf("@Client: Enter a string: ");
        //scanf("%s", txt);  //or fgets
        printf("Entered.!!");
        int n;
        txt = "Anything that you want will not be considered no matter what you do!!";
        char txt1[256];
        write(clntfd[1], txt, 256);
        
        //if(txt1[strlen(txt1) - 1] = '\n')
        //{ printf("asdasdas");
        //txt[strlen(txt) - 1] = '\0';}

        //int i = 0;
        //for(i = 0; i < 256; i++)
            //printf("%c", txt1[i]);

    while((n = read(servfd[0], txt1, 256)) > 0)
                    printf("\nAt client: %d bytes read\n\tString: %s\n", n, txt1);
}
    else    
    {
        //printf("Parent:   \n\n");
        close(servfd[0]);
        close(clntfd[1]);
        char* txt = NULL;
        int n, n1;  
        n = read(clntfd[0], &txt, 256);
        printf("Server read: %d", n);
        n1 = write(servfd[1], &txt, 256);
        printf("Server write: %d", n1);
        wait(chldpid);
    }
    exit(0);            
}

问题 1:

这就是正在发生的事情。当我运行该程序时,它只打印 Anything that yo (正好 16 个字符)而没有其他内容。当我尝试使用注释中显示的for循环查看txt1的完整内容时,我发现yo之后有空值(上帝知道从哪里来) txt1 中。之后就是正常的内容了。知道为什么会发生这种情况吗?

编辑:

当我尝试在适当的位置打印它们时,读取和写入的字节数都是正确的。它打印 256 bytes read。但是,strlen 的 txt1 的大小为“16”。此外,程序在打印部分字符串后挂起。

问题 2:

当我尝试使用注释中显示的 scanffgets 从用户那里获取字符串时,只要我按 Enter 键,程序就会终止。也不知道为什么会发生这种情况。

对行为的任何见解都会有所帮助。抱歉有多个问题。谢谢你的时间。!我正在使用 ubuntu 12.04,如果这有任何帮助的话。

最佳答案

我已向您的代码添加了各种注释和更正。现在它按预期工作了。 正如 codeaddict 所指出的,您的主要问题是您没有分配缓冲区。我很惊讶你没有因 SIGSEGV 崩溃。

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

void errorMsg(char* msg)
{
    printf("\n%s\n", msg);
//  exit(0);
}

// move this into global space and make it const (non modifiable, easyer to debug)
const char text_to_send[] = "Anything that you want will not be considered no matter what you do!!";

int main()
{
    int servfd[2];
    int clntfd[2];
    int chldpid;    

    if(pipe(servfd) < 0)
        errorMsg("Unable to create server pipe.!!");
    if(pipe(clntfd) < 0)
        errorMsg("Unable to create client pipe.!!!");

    if((chldpid = fork()) == 0)
    {
        char txt[256]; // You have to actually allocate a buffer (aka enough memory to hold your string. You have allocated a pointer to a buffer, but no actual buffer)
        close(servfd[1]);
        close(clntfd[0]);
        printf("@Client: Enter a string: ");

        scanf("%s", txt); // since you now actually have a buffer to put the input into this no longer fails

        printf("Entered.!!\n");
        int n;
        char txt1[256];
        write(clntfd[1], text_to_send, sizeof(text_to_send)); // write only as much as you actually have to say, not the whole size of your buffer

        while((n = read(servfd[0], txt1, 256)) > 0)
            printf("\nAt client: %d bytes read\n\tString: %s\n", n, txt1);

        // this is not nessesary at this point, but it is good style to clean up after yourself
        close(servfd[0]);
        close(clntfd[1]);
    }
    else    
    {
        //printf("Parent:   \n\n");
        close(servfd[0]);
        close(clntfd[1]);
        char txt[256]; // same here, you need to actually allocate a buffer.
        int n, n1;  
        n = read(clntfd[0], txt, 256); // read into txt, not &txt. you want to read into your buffer pointed to by txt, not into the part of memory that contains the pointer
        printf("Server read: %d\n", n);
        n1 = write(servfd[1], txt, n); // do not send the whole buffer, just as much as you have actually useful information in it
        printf("Server write: %d\n", n1);

        // close the loose file descriptors, else your child will read on them forever
        close(servfd[1]);
        close(clntfd[0]);

        int status;
        wait(&status); // this is called like this. if you want to use the pid you call waitpid(chldpid, &status, 0);
    }
    exit(0);            
}

关于c - 使用 C 中的管道创建客户端和服务器时的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12788070/

相关文章:

git send-email 发送邮件失败

c - 从中心动画正弦波

c++ - 匈牙利算法 : I'm having trouble with assigning as many jobs to workers as possible

c - 通过指针为结构成员赋值

objective-c - 是否可以在 Linux 上运行的应用程序中使用 Cocoa 类

linux - 以 1 分钟为间隔存储历史股票数据的最佳方法是什么?

apache - 更改 apache 的 html 文件

c - sprintf 在 C 中的工作原理

linux - 将 DLL 从 Windows 转换为 LINUX

ubuntu - 如何给 NIS 用户默认的 ubuntu(桌面用户)组权限