码迷,mamicode.com
首页 > 系统相关 > 详细

Linux - 进程控制 代码(C)

时间:2017-04-25 15:08:28      阅读:269      评论:0      收藏:0      [点我收藏+]

标签:else   fgets   程序   csdn   sys   hello   content   char   地址   

进程控制 代码(C)


本文地址:http://blog.csdn.net/caroline_wendy


输出进程IDgetpid().

代码:

/*By C.L.Wang
 * Eclipse CDT
 * Ubuntu 12.04
 * 2014.10.5*/

#include "apue.h"
#include "error.h"

int main(void) {
	printf("hello world from process ID %ld\n", (long)getpid());
	exit(0);
}

输出:

hello world from process ID 2260


运行命令程序。 fork()创建进程,execlp()运行命令,父进程等待子进程终止waitpid()

代码:

/*By C.L.Wang
 * Eclipse CDT
 * Ubuntu 12.04
 * 2014.10.5*/

#include "apue.h"
#include "error.h"
#include <sys/wait.h>

int main(void) {
	char buf[MAXLINE];
	pid_t pid;
	int status;

	printf("%% ");
	while (fgets(buf, MAXLINE, stdin) != NULL) {
		if (buf[strlen(buf) - 1] == ‘\n‘) {
			buf[strlen(buf) - 1] = 0;
		}

		if ((pid = fork()) < 0) {
			err_sys("fork error");
		} else if (pid == 0) {
			execlp(buf, buf, (char*) 0);
			err_ret("couldn‘t execute: %s", buf);
			exit(127);
		}

		if ((pid = waitpid(pid, &status, 0)) < 0)
			err_sys("waitpid error");
		printf("%% ");
	}

	exit(0);
}


输出:

技术分享



技术分享

Linux - 进程控制 代码(C)

标签:else   fgets   程序   csdn   sys   hello   content   char   地址   

原文地址:http://www.cnblogs.com/lytwajue/p/6761693.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!