嵌入式Linux作业 shell命令 文件操作 fork子进程 匿名管道

一、解释shell命令
  • 1、gcc hello.c -o hello:将hello.c文件编译生成可执行文件hello
  • 2、./hello:执行当前文件夹下的hello文件
  • 3、gdb hello:用gdb调试hello程序


二、解释程序中指定的句子的功能
  • 1、$(CC)$^ -o $@
将所有不重复的依赖文件编译编译成可执行文件,以目标文件的完整名称命名
  • 2、fd=open("temp.log",O_RDONLY);
以只读方式打开当前文件夹下的temp.log文件
  •     size=read(fd,buffer,sizeof(buffer));
将读取到的文件内容保存到buffer指定的字符串数组中,返回读取的字符个数
  • 3、FILE*fp=fopen("recfile","w");
定义一个名为fp的FEIL类型指针,用来调用fopen()函数,以只写方式打开当前目录下的recfile文件,如果打开成功,将文件起始位置地址返回给fp指针,否则返回NUll
  • 4、execlp("ps","ps","-ef",NULL);
execlp()从PATH 环境变量所指的目录中查找ps命令程序并执行,以全格式查看当前所有进程
  • 5、pid_w=waitpid(pid,NULL,WNOHANG);
父进程以非阻塞方式等待子进程结束,若有子进程退出,则waitpid返回子进程识别码pid;若没有子进程推出,则waitpid返回0
  • 6、int ret = mkfifo(write_fifo_name,S_IRUSR | S_IWUSR);

创建名为write_fifo_name的fifo有名管道文件,一个进程拥有读权限,一个进程拥有写权限



三、(1)

#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <string.h>
int main()
{
        int fd,size;
        char text[]="Neme+Number\n";
        char buffer[50];
        pid_t pid,pid_w;
        pid=fork();
        if(pid < 0)
                exit(1);
        else if(pid == 0)
        {
                fd=open("text.txt",O_RDWR|O_CREAT);
                if(fd == -1)
                {
                        printf("Open or creat text.txt failed.\n");
                }
                write(fd,text,sizeof(text));
                close(fd);
                fd=open("text.txt",O_RDWR);
                if( fd== -1)
                {
                        printf("Open text.txt failed\n");
                        return -1;
                }
                size=read(fd,buffer,sizeof(buffer));
                close(fd);
                printf("%s",buffer);
                exit(0);
        }
        else
        {
                pid_w=wait(NULL);
                //printf("Child exit\n");
        }
        return 0;

}

三、(2)

#include<unistd.h>
#include<sys/types.h>
#include<errno.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main()
{
        int fd[2],readFd;
        pid_t child;
        char text[]="Name+Number\n";
        char readbuffer[100];
        pipe(fd);
        if(fd < 0)
        {
                printf("build failed\n");
                return -1;
        }
        child=fork();
        if(child == -1)
        {
                perror("fork failed");
                exit(1);
        }
        if(child == 0)
        {       close(fd[1]);   //关闭写
                sleep(1);
                readFd=read(fd[0],readbuffer,sizeof(readbuffer));
                printf("%s",readbuffer);
                close(fd[0]);   //关闭读
                exit(0);
        }
        else
        {
                close(fd[0]);   //关闭读
                write(fd[1],text,strlen(text));
                close(fd[1]);   //关闭写
        }
        return (0);
}

猜你喜欢

转载自blog.csdn.net/weixin_41471128/article/details/80031282