【问题标题】:my process doesn't go to the child process我的进程没有进入子进程
【发布时间】:2017-03-07 20:15:57
【问题描述】:

我必须在父进程中获取用户输入数字'n',然后将其传递给子进程。然后子进程获取'n'用户输入值并将它们存储在数组中。然后调用线程并将此数组作为参数发送。线程将数组中的所有值相加并将其发送回打印它的子进程。

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

   void *sum(void *a)
 {printf("in thread" );
int * arr=(int *)a;
int i;
int sum=0;
int size=sizeof(arr)/sizeof(arr[0]);
for(i=0;i<size;i++)
{
    sum=sum +arr[i];
}
pthread_exit(sum);
 }
int main()
{
int pipefd[2];
pid_t childpid;
pthread_t tid;

pipe(pipefd);
int r;
int n;

childpid=fork();


if (0==childpid)
{


    printf("in child process" );
    close(pipefd[1]);
    read(pipefd[0],r,sizeof(int));

    close(pipefd[0]);
    int *ret;
    int a[r];
    int i;

    for (i = 0; i <r; i++)
    {   printf("enter values: ");
        scanf("%d",&a[i]);
    }



    pthread_create(&tid,NULL,sum,(void *)a);
    pthread_join(tid,(void *)&ret);
            printf("%d",*ret );


}
else
{   printf("in parent process" );
printf("enter a number" );
    scanf("%d",&n);
    close(pipefd[0]);
    write(pipefd[1],n,sizeof(int));
    close(pipefd[1]);

}
return 0;
 }

我检查了这段代码十几次,似乎没有任何问题。进程在取'n'的值后停止。子进程永远不会运行。

【问题讨论】:

    标签: pthreads pipe ipc


    【解决方案1】:

    readwrite 都希望接收要使用的缓冲区的内存地址。您需要获取要填充的变量的地址。

    例如

    write(pipefd[1], &n, sizeof(int));
    

    read(pipefd[0], &r, sizeof(int));
    

    顺便说一句,子进程很可能正在运行。只是您的 r 的值返回为 0。简单的调试技巧:使用 fprintf(stderr, "stuff to print"); 在各个阶段检查您的结果。例如,您可以轻松验证子进程是否正在运行。

    【讨论】:

    • 好的,现在子进程中的 scanf() 将不起作用。'输入值'出现 n 次,但没有地方输入这些值。我把 fprintf 放在线程函数中,现在谢谢我知道线程至少在运行
    • 查看这个 SO 帖子:stackoverflow.com/questions/26687602/…
    • 答案说他从未在子进程中使用标准输入。但我的问题是我必须在子进程中接受用户输入
    • 你可以自己传递一个文件描述符。 dup 标准输入到不同的东西。您可以从中读取或尝试将其还原回子进程中的标准输入。
    • dup使用标准输入等stackoverflow.com/questions/9084099/…查看这篇文章
    猜你喜欢
    • 2014-05-11
    • 1970-01-01
    • 1970-01-01
    • 2017-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多