网友通过本文主要向大家介绍了深入浅出html5编程,深入浅出cuda编程,深入浅出数据分析,深入浅出,深入浅出的意思等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com
深入浅出《Unix环境高级编程》:Unix基础知识(三)
有些汗颜~,一年半都没有更新了,来了一家新单位,做了自己如愿以偿的嵌入式,回过头来想想,其实也没什么的;
这次我继续,深入浅出的unix环境高级编程系列,希望能坚持下去:)
1、程序和进程
其实这两个概念很好解释,程序是存储在磁盘上的可执行文件;进程是这个可执行文件运行起来再内存中的状态;
举一个不太形象的例子吧;程序和进程的关系像汽车,汽车停在车库就是程序,跑起来的状态就是进程了;
2、进程号PID
在unix和类Unix系统中用进程号标识一个进程;是个非负整数;
可以写一个简单的程序打印一下PID的值,代码如下:
编译语句是gcc -o pid pid.c
- #include
- #include
- #include
- int main(int argc, char * argv[])
- {
- pid_t pid = 0;
- pid = getpid();
- printf("this proccess id is %d\n", pid);
- return 0;
- }
执行结果是:
看着样子是每次的PID都不大一样;这样可以保证每次启动的时候检查一下是不是已经启动了这个程序了;一般讲pid存储成一个.pid的文件,来检测是否已经启动这个程序了;
- ./pid
- this proccess id is 24047
- ./pid
- this proccess id is 24048
- ./pid
- this proccess id is 24050
- ./pid
- this proccess id is 24051
- # ./pid
- this proccess id is 24052
改造了一下程序,如下:
运行程序之后会在当前目录创建一个freesir.pid的文件,如果多次运行会报已经运行的错误;大概就是这样子啦;
- #include
- #include
- #include
- #include
- #include
- #include
- int main(int argc, char * argv[])
- {
- pid_t pid = 0;
- char * pidfile = "./freesir.pid";
- pid = getpid();
- int fd = 0;
- char pids[16] = {0};
- if(access(pidfile, F_OK) != -1)
- {
- printf("this program is already run in system.\n");
- return -1;
- }
- fd = open(pidfile, O_TRUNC | O_CREAT | O_RDWR);
- if(fd < 0)
- {
- printf("open pid file error!\n");
- return -2;
- }
- sprintf(pids, "%d", pid);
- if(write(fd, pids, strlen(pids)) != strlen(pids))
- {
- printf("write pid file error!\n");
- return -3;
- }
- sleep(10);
- unlink(pidfile);
- close(fd);
- printf("this proccess id is %d\n", pid);
- return 0;
- }
3、进程控制
这里就简单介绍一下进程控制就好,unix环境高级编程后面会有更详细的介绍;
示例代码中只是写了一个简单的shell封装,我们还是分别写俩小程序单独解释吧;
上面的程序会打印父子进程的pid,可以看得出来,子进程是返回的0,且可以用getpid获取他的子进程ID;父进程返回的是子进程的PID;
- #include
- #include
- #include
- int main(int argc, char * argv[])
- {
- pid_t pid = 0;
- int status = 0;
- pid = fork();
- if(pid < 0)
- {
- printf("fork error!\n");
- return 0;
- }
- else if(pid == 0)
- {
- printf("i'm the child proccess. pid = %d\n", getpid());
- sleep(5);
- exit(127);
- }
- else if(pid > 0)
- {
- printf("i'm parent prccess. pid = %d, childpid = %d\n", getpid(), pid);
- }
- pid = waitpid(pid, &status, 0);
- if(pid < 0)
- {
- printf("waitpid error!\n");
- }
- return 0;
- }
最后使用waitpid等待子进程退出;出错了这里只是简单打印,其实是需要使用waitpid的三个宏来确性子进程的退出状态的;
这些以后可以在写,不展开啦;
- WIFEXITED(status)
- WEXITSTATUS(status)
- WIFSTOPPED(status)
今天就看这么多吧,越看越觉得linux很强大,折服。。。。