درخواست یک برنامه ساده به زبان C (ساختار parent و child)
دوستانِ مسلط به زبان 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);
}
ممنون می شم اگه از اساتید یکی کمکم کنه.
نقل قول: درخواست یک برنامه ساده به زبان C (ساختار parent و child)
سلام
برنامه ای که می خواهید در لینک زیر قرار داره باکمی تغییر
http://linux.die.net/man/2/pipe
البته تابع getch را از لینک زیر گرفتم
http://stackoverflow.com/questions/3...-of-c-in-linux
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
/* reads from keypress, doesn't echo */
int getch(void)
{
struct termios oldattr, newattr;
int ch;
tcgetattr( STDIN_FILENO, &oldattr );
newattr = oldattr;
newattr.c_lflag &= ~( ICANON | ECHO );
tcsetattr( STDIN_FILENO, TCSANOW, &newattr );
ch = getchar();
tcsetattr( STDIN_FILENO, TCSANOW, &oldattr );
return ch;
}
int
main(int argc, char *argv[])
{
int pipefd[2];
pid_t cpid;
char buf;
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
cpid = fork();
if (cpid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (cpid == 0) { /* Child reads from pipe */
close(pipefd[1]); /* Close unused write end */
while (read(pipefd[0], &buf, 1) > 0)
write(STDOUT_FILENO, &buf, 1);
write(STDOUT_FILENO, "\n", 1);
close(pipefd[0]);
_exit(EXIT_SUCCESS);
} else { /* Parent writes argv[1] to pipe */
close(pipefd[0]); /* Close unused read end */
char ch = 0;
while((ch = getch()) != 10){
write(pipefd[1], &ch , 1);
}
close(pipefd[1]); /* Reader will see EOF */
wait(NULL); /* Wait for child */
exit(EXIT_SUCCESS);
}
}
نقل قول: درخواست یک برنامه ساده به زبان C (ساختار parent و child)
بسیار بسیار از لطف شما سپاسگزارم.
اما ساختار برنامه مورد نیازم تغییر کرد و حالا دستور execl وارد ماجرا شده که کار رو برام پیچیده تر کرده. صورت سوال رو اینجا پست کردم. آیا می تونید کمکی بفرمایید؟