linux命令:打印正在运行的进程(ps -elf),通过名字搜索进程:(ps -elf | grep (关键字));
1.获取ID(getpid(void))
用getpid来获取进程id,getppid来获取父进程id
1 #include <stdio.h>
2 #include <sys/types.h>
3 #include <unistd.h>
4
5 int main()
6 {
7 pid_t pid = getpid();
8 printf("%d\n",pid);
9 printf("%d\n",getppid()); //
10 while(1)
11 return 0;
12 }
进程创建(fork(void))
功能:创建子进程,fork的奇妙之处在于他被调用一次,却返回两次,它可能有三种不同的返回值
1.在父进程中,fork返回新创建的子进程ID;
2.在子进程中,fork返回0;
3.如果出现错误,fork返回一个负值
多进程拷贝代码:
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <sys/types.h>
4 #include <unistd.h>
5 #include <string.h>
6 #include <unistd.h>
7 #include <sys/stat.h>
8 #include <fcntl.h>
9
10 int main(int argc,char *argv[])
11 {
12 int num = 5, i;
13 int byte_count = 0;
14 char buf[128] = {0};
15 ssize_t ret;
16 int fd_from = open(argv[1],O_RDONLY);
17 if(-1 == fd_from)
18 {
19 perror("open");
20 exit(1);
21 }
22 //计算源文件长度
23 int length = lseek(fd_from,0,SEEK_END);
24 int each_len = length / num;
25 close(fd_from);
26
27 int fd_to = open(argv[2], O_WRONLY | O_CREAT, 00400 | 00200);
28 if(-1 == fd_to)
29 {
30 perror("open1");
31 exit(2);
32 }
33 close(fd_to);
34 pid_t pid;
35 for(i = 1; i <= num; i++)
36 {
37 pid = fork();
38 if(-1 == pid)
39 {
40 perror("fork");
41 exit(1);
42 }
43 else if(0 == pid)
44 {
45 break;
46 }
47 }
48
49 if(i == num + 1) //父进程
50 {
51 //回收子进程
52 printf("父进程\n");
53 }
54 else if(i == 5)
55 {
56 fd_from = open(argv[1],O_RDONLY);
57 if(-1 == fd_from)
58 {
59 perror("open1");
60 exit(1);
61 }
62 fd_to = open(argv[2],O_WRONLY);
63 if(-1 == fd_to)
64 {
65 perror("open2");
66 exit(2);
67 }
68 lseek(fd_from, (i - 1)*each_len,SEEK_SET);
69 lseek(fd_to, (i - 1)* each_len,SEEK_SET);
70 while(1)
71 {
72 ret = read(fd_from,buf,sizeof(buf) - 1);
73 if(-1 == ret)
74 {
75 perror("read");
76 }
77 else if(0 == ret)
78 {
79 printf("第五个进程拷贝完毕\n");
80 close(fd_from);
81 close(fd_to);
82 break;
83 }
84 ret = write(fd_to,buf,ret);
85 if(-1 == ret)
86 {
87 perror("write");
88 }
89 memset(buf, 0, sizeof(buf));
90 }
91 }
92 else
93 {
94 fd_from = open(argv[1],O_RDONLY);
95 if(-1 == fd_from)
96 {
97 perror("open1");
98 exit(1);
99 }
100 fd_to = open(argv[2],O_WRONLY);
101 if(-1 == fd_to)
102 {
103 perror("open2");
104 exit(2);
105 }
106 lseek(fd_from, (i - 1)*each_len,SEEK_SET);
107 lseek(fd_to, (i - 1)* each_len,SEEK_SET);
108 while(1)
109 {
110 if(each_len - byte_count < sizeof(buf) - 1)
111 {
112 ret = read(fd_from, buf, each_len - byte_count);
113 {
114 if(-1 == ret)
115 {
116 perror("read");
117 }
118 }
119 }
120 else
121 {
122 ret = read(fd_from, buf, sizeof(buf) - 1);
123 if(-1 == ret)
124 {
125 perror("read");
126 }
127 }
128 byte_count += ret;
129 ret = write(fd_to,buf,ret);
130 if(-1 == ret)
131 {
132 perror("write");
133 }
134 if(byte_count == each_len)
135 {
136 printf("第%d个进程拷贝完毕\n",i);
137 close(fd_from);
138 close(fd_to);
139 break;
140 }
141 memset(buf,0,sizeof(buf));
142 }
143 }
144 return 0
145 }
exec函数族 (用被执行的程序替换调用它的程序)
区别:
fork 创建一个新的进程,产生一个新的PID
exrc 启动一个新程序,替换原有的进程,因此进程的PID不会改变