写在前面:
/**兄弟们,近些日子得到了一些不好的反馈,有人说一些同学在传抄我的答案。我表示很惊慌。。。。。。
可能是因为时间的原因写不完,又或者是因为比较难不会。但无论什么原因大家一定不要完全照抄啊。因为一方面要是被老师发现了,你凉了我也得凉。。。。。。
我本是想记录下学习过程的笔记,兄弟们要是有不理解的话要是我还记得内容可以同我一起探讨,但是我的答案也不一定是对的!也不一定是最佳的,你改一改不就是更好了嘛!
ps:实在赶时间起码改动一些吧,听说有代码里面连包的名字都不改的,_ . _ 。
还是熟悉的 com.ctgu.zyj。害,大家都是学计算机的,麻烦cv也专业一点呀!
*/
一、回忆一下linux执行程序指令
1.编译一个c程序:
gcc test.c -o test
2.执行这个c程序:
./test
二、linux嵌入式_test_5
1.请利用Fork(),EXEC()功能在一个程序中运行“ps -axf”命令。
#include <stdio.h>
#include <unistd.h>
int main(void)
{
int flag;
pid_t pid;
pid = fork();
if(pid==0) {
printf("in child process:\n");
//执行ps命令
flag = execl("/bin","ps", "-axf", NULL);
if(flag == -1)
printf("exec error!\n");
}
printf("in parent process :\n");
return 0;
}
2.编写一个守护进程,利用守护进程向日志文件循环写入一些信息比如当前时间等。
/*守护进程程序 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include<time.h>
int main() {
pid_t pid ;
int i, fd ;
time_t t;
pid = fork() ;//第一步,创建子进程
if(pid < 0) {
printf("fork error\n") ;
exit(1) ;
} else if (pid > 0)
exit(0) ;
setsid() ;//第二步,创建新会话
chdir("/") ;//改变当前工作目录为跟目录
umask(0) ;//设置文件权限掩码
for(i = 0; i < getdtablesize(); ++i) {
close(i) ;//关闭文件权限描述符
}
//守护进程每隔10s打日志
while(1) {
//获取系统时间并把时间存到数组中
time_t t;
char buf[128];
memset(buf,0,sizeof(buf));
struct tm *tmp;
t = time(NULL);
tmp = localtime(&t);
strftime(buf,sizeof(buf),"%Y-%m-%d %H:%M:%S",tmp);
if (fd = open("/tmp/daemon.log", O_CREAT|O_WRONLY|O_APPEND, 0600) < 0) {
printf("open file error\n") ;
exit(1) ;
}
write(fd, buf, strlen(buf)+1) ;
close(fd) ;
sleep(10) ;
}
exit(0) ;
}
3.编写一个多进程程序,共运行三个进程,第一个子进程只运行“ls”命令后退出,第二个子进程运行“ps”命令后,等待5秒退出,父进程阻塞等待第一个子进程结束,输出提示信息,然后非阻塞等待第二个子进程结束,输出提示信息。
/*多进程程序 */
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void) {
pid_t child1, child2, child;
/*创建两个子进程*/
child1 = fork();
/*子进程 1 的出错处理*/
if (child1 == -1) {
printf("Child1 fork error\n");
exit(1);
} else if (child1 == 0) { /*在子进程 1 中调用 execlp()函数*/
printf("In child1: execute 'ls -l'\n");
if (execlp("ls", "ls", "-l", NULL) < 0) {
printf("Child1 execlp error\n");
}
}else{ /*在父进程中再创建进程 2,然后等待两个子进程的退出*/
child2 = fork();
if (child2 == -1) { /*子进程 2 的出错处理*/
printf("Child2 fork error\n");
exit(1);
} else if(child2 == 0) { /*在子进程 2 中使其暂停 5s*/
printf("In child2: execute ps");
if(execlp("ps", "ps", "-o", "pid,ppid,pgrp,session,tpgid,comm", NULL)<0) {
printf("Child2 execlp error");
}
printf("child2 has slept for 5 seconds and then exit\n");
sleep(5);
exit(0);
}else{
printf("In father process:\n");
child = waitpid(child1, NULL, 0); /* 阻塞式等待 */
if (child == child1) {
printf("Get child1 exit code\n");
} else {
printf("Error occured!\n");
}
do {
child = waitpid(child2, NULL, WNOHANG ); /* 非阻塞式等待 */
if (child == 0) {
printf("The child2 process has not exited!\n");
sleep(1);
}
} while (child == 0);
if (child == child2) {
printf("Get child2 exit code\n");
} else {
printf("Error occured!\n");
}
}
exit(0);
}
}