【发布时间】:2016-06-02 17:50:02
【问题描述】:
我正在编写一个代码,其中孩子和父母应该互相提供时间信息,接收者应该打印它。当我在父进程上找到时间并尝试在父进程上打印它时它工作正常。但是当我尝试通过管道发送它会写一行带有奇怪的问号和 az 字母的行。我评论了最后一行,以防有人试图执行代码。抱歉代码乱七八糟,但我无法在我当前的键盘上修复它。
#include<stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/time.h>
#include<signal.h>
#include<stdint.h>
#include<string.h>
#include<time.h>
void formatted_time(char* sender_name, char* receiver_name, char output[]);
void formatted_time( char* sender_name , char* receiver_name, char output[])
{
struct timeval tv;
time_t nowtime;
struct tm *nowtm;
char tmbuf[80];
gettimeofday(&tv, NULL);
nowtime = tv.tv_sec;
nowtm = localtime(&nowtime);
strftime(tmbuf,80 , "%Y-%m-%d %H:%M:%S",
nowtm);
sprintf(output, "%s: Time at %s is %s.", receiver_name, sender_name, tmbuf);
}
int main(int argc, char** argv)
{
char* parent="Parent";
char* child1="Child1";
char* child2="Child2";
char result[80];
char buffer[80];
int firstchild,secondchild,read1,read2,read3;
firstchild=fork();
int mypipe[2];
int mypipe2[2];
int mypipe3[2];
if(pipe(mypipe) == -1) {
perror("Pipe failed");
exit(1);
}
if(firstchild == 0) //first child
{
close(mypipe[1]); //Closing the output of pipe
sleep(3);
read1=read(mypipe[0],buffer,sizeof(buffer));
printf("%s\n",buffer);
}else{
secondchild=fork(); //Creating second child
if(secondchild == 0) //2nd child
{
sleep(6);
}else{ //Parent
close(mypipe[0]); //Closing the input of pipe
formatted_time(parent,child1,result);
write(mypipe[1],result,strlen(result)+1);
//printf("%s\n",result);
【问题讨论】:
-
你在哪里
read来自管道?我在您的代码中的任何地方都看不到它。此外,使用sleep是尝试同步进程的一种非常粗糙的方法,并且在某些时候肯定会中断。 -
我以为这写到了管道的另一端。写(mypipe[1],结果,strlen(结果)+1); .我可能错了,但这就是我在书中学到的方法
-
是的,那是
write调用,但是read在哪里? -
哇,我忘记加了。但它仍然只写了一个问号。
-
您的代码似乎不完整。