fork_example.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
pid_t pid;
/*fork another porcess*/
pid = fork();
if(pid<0) /*error occurred*/
{
fprintf(stderr, "Fork Failed");
exit(-1);
}
else if(pid==0) /*child process*/
{
execlp("/bin/ls","ls",NULL);
}
else /*parent process*/
{
wait(NULL);
printf("Child Complete\n");
exit(0);
}
}
執行結果
ordinary_pipe.c
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#define BUFFER_SIZE 25
#define READ_END 0
#define WRITE_END 1
int main(void)
{
char write_msg[BUFFER_SIZE] = "Greetings";
char read_msg[BUFFER_SIZE];
int fd[2];
pid_t pid;
if(pipe(fd)==-1)
{
fprintf(stderr,"Pipe failed");
return 1;
}
pid = fork();
if(pid<0)
{
fprintf(stderr, "Fork Failed");
return 1;
}
if(pid>0)
{
close(fd[READ_END]);
write(fd[WRITE_END], write_msg, strlen(write_msg)+1);
close(fd[WRITE_END]);
} else
{
close(fd[WRITE_END]);
read(fd[READ_END], read_msg, BUFFER_SIZE);
printf("\nread %s\n", read_msg);
close(fd[READ_END]);
}
return 0;
}
執行結果
沒有留言:
張貼留言