实验六 进程基础

2021/5/30 7:26:37

本文主要是介绍实验六 进程基础,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

项目 內容
这个作业属于哪个课程 班级课程主要链接
这个作业的要求在哪里 作业要求链接
学号-姓名 18043212-邓锐
作业学习目标 1.掌握Linux系统环境C语言编程概念 2.学习Linux系统进程概念

1请举例说明静态链接库的创建与使用
举例

int add(int a,int b){
return a+b;
}
//文件名:sub.c,减法
int sub(int a,int b){
return a-b;
}
//文件名:main.c
#include <stdio.h>
int add(int a,int b);
int sub(int a,int b);
int main(){
printf("3 + 1 = %d\n",add(3,1));
printf("3 - 1 = %d\n",sub(3,1));
return 0;
}




2.请举例说明共享库的创建与使用。

/文件名:common.h
#ifndef _COMMON_
#define _COMMON_
int add(int a,int b);
int sub(int a,int b);
#endif
//文件名:add.c
int add(int a,int b){
return a+b;
}
//文件名:sub.c
int sub(int a,int b){
return a-b;
}
//文件名:main.c
#include<stdio.h>
#include"common.h"
int main(){
printf("3+1=%d\n",add(3,1));
printf("3-1=%d\n",sub(3,1));
}



3.编程实现一个简单文件复制命令。

//文件名:mycp.c
#include <unistd.h> 
#include <sys/types.h> 
#include <sys/stat.h> 
#include <fcntl.h>
#include <stdio.h> 
#define BUFFERSIZE 4096 
int main(int argc, char* argv[]) {
if (argc != 3) { 
printf("usage:\n mycp src dst\n"); 
return 1;
}
int srcfd = open(argv[1], O_RDONLY); 
if (srcfd == -1) { 
perror("open");
return 1; 
}
int dstfd = open(argv[2], O_CREAT | O_WRONLY, 0666); 
if (dstfd == -1) { 
close(srcfd); 
perror("open"); 
return 1; 
}
int len = 0;
char buffer[BUFFERSIZE] = {0}; 
while((len = read(srcfd, buffer, BUFFERSIZE)) > 0) {
if (write(dstfd, buffer, len) != len) {
perror("write error"); 
return 1; 
}
}
if (len < 0) {
perror("read error"); 
return 1;
}
close(srcfd); // 关闭文件 
close(dstfd);
return 0; 
}



复制后test

4.使用fork创建一个子进程,进程创建成功后父子进程分别输出不同的内容。

///文件名:fork1.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(){
pid_t pid;
printf("[%d]:Begin! \n",getpid());
fflush(NULL);
pid = fork();
if(pid<0)
{
perror("fork()");
exit(1);
}
else if(pid > 0)
{
printf("[%d]:Parent process if working!\n",getpid());
}
else
{
printf("[%d]:Child process if working!\n",getpid());
}
printf("[%d]:Finish!\n",getpid());
return 0;
}





5.使用fork创建多个子进程。


6在 fork 之前以写的方式创建了一个文件 test.txt。然后 fork 出的子进程立即向文件中写入“world”,然后睡眠5秒。而父进程在 fork 后睡眠3秒后向 test.txt 写入 "hello",并关闭描述符。子进程恢复后,又向 test.txt 文件中写入 "lalala"后关闭描述符,结束




7.分别在主函数中使用execvp启动ls命令以及使用fork函数产生子进程调用execvp启动ls。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(){
char* argv[] = {"ls","-l",NULL};
if (execvp("ls",argv) == -1){
perror("exec");
return 1;
}
return 0;
}



(2)使用fork函数产生子进程调用execvp启动ls命令:


8创建5个僵尸进程,并在终端通过ps axf命令查看僵尸进程信息




9通过wait来清理僵尸进程。




这篇关于实验六 进程基础的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程