第四个,获取pid,每一个程序的实例就是进程,他有自己的process ID
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
printf("hello world from process ID %d\n",getpid());
exit(0);
}
第五个
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#define MAXLINE 32
int main(void)
{
char buf[MAXLINE];
pid_t pid;
int status;
printf("%%");
while(fgets(buf,MAXLINE,stdin)!=NULL)
{
buf[strlen(buf)-1]=0;
if((pid=fork())<0) //创建一个新的进程
perror("fork error ");
else if (pid==0) //如果是子进程的话pid是等于0的
{
execlp(buf,buf,(char*)0);//从当前PATH中找符合file的文件名最后一个参数用空指针,指向成功会去加载代码不会回来
perror("couldn't execute :command");
exit(127); //127没有找到命令
}
if((pid =waitpid(pid ,&status,0))<0)//查看子进程有么有结束
perror("waitpid error");
printf(" %%");
}
exit(0);
}
程序1-6 strerror和perror用法
#include<errno.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int argc ,char** argv)
{
fprintf(stderr,"EACCES: %s\n",strerror(EACCES));//他的报错于EACCES有关
errno=ENOENT;
perror(argv[0]); //当前的errno的值是多少他就报什么错
exit(0);
}
/* output:
EACCES: Permission denied
./test: No such file or directory
*/
程序1-7 打印用户ID组ID
#include<errno.h>
#include<stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include<stdlib.h>
#include<string.h>
int main(int argc ,char** argv)
{
printf("uid=%d ,gid=%d\n",getuid(),getgid());
exit(0);
}
read command from stdin and run
#include<errno.h>
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<signal.h>
#include<stdlib.h>
#include<string.h>
#define MAXLINE 64
static void sig_int(int);
int main(int argc ,char** argv)
{
char buf[MAXLINE];
pid_t pid;
int status;
if(signal(SIGINT,sig_int)==SIG_ERR) //信号函数设置当我按下 pause就会触发函数
perror("SIGNAL err");
printf("%%1");
while(fgets(buf,MAXLINE,stdin)!=NULL)
{
buf[strlen(buf)-1]=0;
if((pid=fork())<0)
perror("fork err");
else if(pid==0)
{
execlp(buf,buf,(char*) 0);
perror("couldn't execute: command");
exit(127);
}
if((pid=waitpid(pid,&status,0))<0)
perror("waitpid err");
printf("%%2");
}
exit(0);
}
void sig_int(int signo)
{
printf("interrupt\n%%3");
}
/*
makefile mylen.c test test.c
%2ds
couldn't execute: command: No such file or directory
%2^Cinterrupt
ds
couldn't execute: command: No such file or directory
%3%3%2s
couldn't execute: command: No such file or directory
%2^Cinterrupt
d
couldn't execute: command: No such file or directory
*/
本文介绍了如何使用C语言获取进程ID(PID),并通过fork()和execlp()实现程序实例间的父子进程关系。此外,展示了strerror()和perror()的用法,以及用户ID和组ID的获取。程序还演示了如何读取命令并处理中断信号。
7310

被折叠的 条评论
为什么被折叠?



