/*start from the very beginning,and create greatness
@name:Chuangwei Lin
@E-mail:979951191@qq.com
@brief:get pid and get ppid
*/
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
// int main(int argc, char const *argv[])
// {
// pid_t pid,ppid;
// //get the pid and ppid(parent process ID)
// pid = getpid();
// ppid = getppid();
// printf("the pid is :%d\n",pid);
// printf("the ppid is :%d\n",ppid );
// return 0;
// }
/*use fork() to create a process*/
// int main(int argc, char const *argv[])
// {
// pid_t pid;
// //
// pid = fork();
// if (-1 == pid )
// {
// printf("process create fail!\n");
// return -1;
// }
// else if ( pid == 0)
// {
// //code in child process
// printf("child process:fork return :%d,ID :%d,parent process ID:%d\n", pid,getpid(),getppid());
// }
// else
// {
// //code in parent process
// printf("parent process:fork return :%d,ID :%d,parent process ID:%d\n",pid,getpid(),getppid());
// }
// return 0;
// }
/*use pipe to send simple messsage*/
#include <stdlib.h>
#include <string.h>
int main(int argc, char const *argv[])
{
int result=-1;//the result of pipe
int fd[2],nbytes;//file descriptor,and the number of return bytes
pid_t pid;
char string[]="Hello ,I am Lin";
char readbuffer[80];
//the file descriptor 1 is used to write ,2 is used to read
int *write_fd=&fd[1];
int *read_fd=&fd[0];
result=pipe(fd);//create a pipe
if (-1==result)
{
printf("create pipe fail\n");
return -1;
}
pid =fork();
if (-1==pid)
{
printf("create process fail\n");
return -1;
}
if (0==pid)//child process
{
close(*read_fd);
result=write(*write_fd,string,strlen(string));
//write message to pipe
}
else//parent process
{
close(*write_fd);
nbytes=read(*read_fd,readbuffer,sizeof(readbuffer));
//read message from pipe
printf("receive %d bytes from pipe:%s\n",nbytes,readbuffer );
}
return 0;
}
阅读(1258) | 评论(0) | 转发(0) |