bababarghi
جمعه 17 مهر 1394, 13:02 عصر
دوستانِ مسلط به زبان C به برنامه ای نیاز دارم که یه یک ساختار parent و child تعریف کنه (استفاده از fork) و هر کلیدی که کاربر در parent فشار می ده به صورت مستمر در childنشون داده بشه (در یک while loop باشه)
نمونه های زیادی رو دیدم که از pipe استفاده شده بود اما نتونستم pipe رو با loop ام ترکیب کنم. به عنوان مثال این کد زیر هست اما نمی دونم چطور می تونم حلقه ای رو برنامه اضافه کنم که هر رشته ای رو parent می فرسته، child اونرو همون لحظه نمایش بده
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
int main(void)
{
int fd[2], nbytes;
pid_t childpid;
char string[] = "Hello, world!\n";
char readbuffer[80];
pipe(fd);
if((childpid = fork()) == -1)
{
perror("fork");
exit(1);
}
if(childpid == 0)
{
/* Child process closes up input side of pipe */
close(fd[0]);
/* Send "string" through the output side of pipe */
write(fd[1], string, (strlen(string)+1));
exit(0);
}
else
{
/* Parent process closes up output side of pipe */
close(fd[1]);
/* Read in a string from the pipe */
nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
printf("Received string: %s", readbuffer);
}
return(0);
}
ممنون می شم اگه از اساتید یکی کمکم کنه.
نمونه های زیادی رو دیدم که از pipe استفاده شده بود اما نتونستم pipe رو با loop ام ترکیب کنم. به عنوان مثال این کد زیر هست اما نمی دونم چطور می تونم حلقه ای رو برنامه اضافه کنم که هر رشته ای رو parent می فرسته، child اونرو همون لحظه نمایش بده
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
int main(void)
{
int fd[2], nbytes;
pid_t childpid;
char string[] = "Hello, world!\n";
char readbuffer[80];
pipe(fd);
if((childpid = fork()) == -1)
{
perror("fork");
exit(1);
}
if(childpid == 0)
{
/* Child process closes up input side of pipe */
close(fd[0]);
/* Send "string" through the output side of pipe */
write(fd[1], string, (strlen(string)+1));
exit(0);
}
else
{
/* Parent process closes up output side of pipe */
close(fd[1]);
/* Read in a string from the pipe */
nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
printf("Received string: %s", readbuffer);
}
return(0);
}
ممنون می شم اگه از اساتید یکی کمکم کنه.