程序在屏幕上显示奇怪的字符

时间:2014-09-06 00:27:59

标签: c linux ubuntu

我正在开发一个客户端 - 服务器程序,这是我的server_2文件,它将与主服务器通信。 程序在运行时会在屏幕上显示这些行。我认为mkfifo之后的那些线是造成这种情况的。

i�e|楬���h�.N=��.8��
i�H��h� ��h� �i���Ǭ��ǬjǬ�dǬ�@��i�P@h�Ǭ���h����h�jǬ��ǬP

结构

typedef struct request req;
struct request
{
    char str[256];
    int client_pid;
    int login; // In case of client, to identify if is logged
    int whois; // To identify who is the client and the server
};

typedef struct answer ans;
struct answer
{
    char str[256];
    int server_pid;
    int type;
    int login;
    int num_users;
};

主:

#include "header.h"

int main(int argc, char *argv[])
{
    int fifo_1, fifo_2;
    struct request req;
    struct answer ans;

    if(argc == 2) // Check if the command was well prompted
    {
        if(strcasecmp(argv[1], "show") == 0 || strcasecmp(argv[1], "close") == 0)
        {
            if(fifo_2 = open("FIFO_SERV", O_WRONLY) == -1) 
            {
                perror("[SERVER_2] Error: on the FIFO_SERVER opening!\n");
                sleep(2);
                exit(EXIT_FAILURE);
            }

            if(mkfifo("FIFO_SERV_2", 0777) == -1) 
            {
                perror("[SERVER_2] Error: on the FIFO_SERVER_2 creation!\n");
                sleep(2);
                exit(EXIT_FAILURE);
            }

            strcpy(req.str, argv[1]); // Copy the argumento to the structure

            write(fifo_2, &req, sizeof(req)); // Write a request to the server
            strcpy(req.str,""); // Clean the string

            fifo_1 = open("FIFO_SERV_2", O_RDONLY); 

            read(fifo_1, &ans, sizeof(ans)); //Read an answ
        }

    //close(fifo_1);
    unlink("FIFO_SERVER_2");
    sleep(2);
    exit(EXIT_SUCCESS);
}

1 个答案:

答案 0 :(得分:4)

运营商===的优先规则构成了行

if(fifo_2 = open("FIFO_SERV", O_WRONLY) == -1) 

相当于

if(fifo_2 = (open("FIFO_SERV", O_WRONLY) == -1))

如果open成功,则基本上将0分配给fifo_2,如果open失败则为1。值0和1也恰好是POSIX标准库实现中标准输入和输出文件描述符的相应值(请参阅File descriptor on wikipedia),因此稍后执行时

write(fifo_2, &req, sizeof(req)); // Write a request to the server

您要么尝试写入标准输入(未定义的行为),要么写入标准输出,具体取决于是否可以打开文件而不是服务器。要解决此问题,您可以使用以下命令替换open表达式:

if((fifo_2 = open("FIFO_SERV", O_WRONLY)) == -1)

然后,您可能必须弄清楚无法打开文件的原因(因为您可能正在写入标准输出,这意味着open失败了。)