【问题标题】:Passing Array through named-pipe in c在c中通过命名管道传递数组
【发布时间】:2014-06-07 12:56:07
【问题描述】:

我正在尝试将 char ** 从父进程传递给子进程。当我尝试打印字符串时,我的程序没有错误地终止......只是终止了。这是我的代码:

我开始:

int main(int argc, char *argv[])
{
    pid_t pid;
    char **args;
    int i;


    if(argc < 3)
    {
         perror("Argc");
         exit(1);
    }

    args = malloc(argc*sizeof(char *));

    for(i=0; i<argc; i++)
    {
        if( i == (argc-1) )
        {
            args[i] = NULL;
            break;
        }

        args[i] = malloc(strlen(argv[i+1])*sizeof(char));
        strcpy(args[i], argv[i+1]);
        printf("%s\n",args[i]);
    }

    if( server_exists() )
    {
    //pipes
    }

    else
    {       
        pid = fork();

        if(pid < 0)
        {
             perror("Fork");
             exit(1);
        }

        else if( pid == 0 )
        {           
             execl("./jobServer", "jobServer", NULL);           
        }   

        else if( pid > 0 )
        {
            for(i=0; i<argc-1; i++)
            {
                printf("%s\n",args[i]);
            }
            send_args(args, argc);
        }   
    }

    return 0;
}

一个有用的功能:

void send_args(char **args, int argc)
{
    int fd, i;
    char *myfifo = "myfifo";
    int total = 0;

    for(i=0; i<argc-1; i++)
    {
        total += (strlen(args[i])) + 1 ;
        printf("%d %s\n",(strlen(args[i])), args[i]);
    }
    printf("asdf %d\n",total);
    mkfifo(myfifo, 0666);

    fd = open(myfifo, O_WRONLY);
    write(fd, args, sizeof(total));
    close(fd);

    unlink(myfifo);
}

子进程(exec "jobServer"):

#define MAX_BUF 2048

int main(int argc, char *argv[])
{
    int fd,i=0;
    char *myfifo = "myfifo";
    char *buf[MAX_BUF];

    if( !server_exists() ) make_server(getpid());

    fd = open(myfifo, O_RDONLY);
    read(fd, buf, MAX_BUF);

    //I can't print these
    printf("%s\n",buf[0]);
    printf("%s\n",buf[1]);
    printf("%s\n",buf[2]);

    close(fd);

    return 0;
}

你能帮忙吗?提前致谢!

【问题讨论】:

    标签: c pipe named-pipes


    【解决方案1】:

    您理解的问题是命名管道就像文件或流一样,因此您可以将字节写入其中。

    当您有一个指针数组(或多维数组)时,这些指针实际上将指向内存中的其他位置(数组之外),因此接收应用程序将跟随这些指针并使用其地址中的任何内容地址空间(与发送者的地址空间不同)。

    因此,您不能只是将数组复制到您的管道/文件/任何东西中,而是必须提取所有数据(按照指针)并单独写入。

    此外,无论total 的实际值如何,sizeof(total) 将始终为 sizeof(int)(可能是 4 或 8)。

    【讨论】:

    • 你的意思是我必须像我的字符串一样多地读写?我可以传递指针的地址,以便能够使用正确的地址和正确的数据吗?
    • 要么这样,要么你必须将所有字符串复制(strcpy/strcat)到你之前分配的一些连续内存中(以某种方式分开,你可以稍后再拆分),然后写那个。跨度>
    • 感谢您的建议!
    • @a_user 不,你不能只将指针发送给另一个进程,这个指针在第二个进程中将无效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多