C语言_文件_进程_进程间通讯 常用函数/命令 + 实例

news2024/7/2 3:34:13

 文件相关命令:

ps -aux|grep init?      //搜索包含init名称的进程
top                     //linux下的资源管理器(动态)

//open 返回的int 是给后面的读/写/光标移动 用的fd,没有open就不能进行后面的操作;
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
close(fd); //关闭文件

// _t 都是返回的int数字;写write,读read,光标移动lseek
ssize_t write(int fd, const void *buf, size_t count);
ssize_t read(int fd, void *buf, size_t count);
off_t lseek(int fd, off_t offset, int whence);

//同时打开两个文件
vimdiff demo1.c demo2.c 

//fopen注意mode就行,有:r r+ w w+ a ,返回的文件指针是给后面的读 写 偏移用
FILE *fopen(const char *pathname, const char *mode);
fclose(FILE *); //关闭文件

//跟上面的差不多一样用
//fread/fwrite(读写的数组,读写的大小,  读写的最大次数?, 读写的文件指针)
                (读写返回次数的区别:读为有效次数,能一次读完就算你写10次,也返回只读1次)
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
size_t fwrite(const void *ptr, size_t size, size_t nmemb,FILE *stream);
int fseek(FILE *stream, long offset, int whence);

fputc();//写入一个字符;
fgetc();//读取一个字符
feof();/检测是否到达文件末尾,到了返回1;文件结束符为EOF=-1;

//注意:读写操作都会使光标偏移,但也可以利用这点来遍历读写文件;
例:
while(!feof(FILE* fd)){
    printf("%c  ",fgetc(FILE* fd));
}

进程相关命令:

getpid(); fork(); vfork();


//_t 一律返回的是int
//获取进程ID 就是pid
pid_t getpid(void);

//fork创建子进程
pid_t fork(void);
//这里返回的是的pid = 0 就是子进程,pid > 0 就是父进程;
//所以可以通过判断pid的值,来区别父子进程需要执行的代码;
//注意fork开辟的子进程,没有等待一说,父子进程谁抢到就先运行谁,
//【子进程为僵尸进程】;
//例:

#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
        pid_t pid;

        int num = 0;
        pid = getpid();
        printf("this pid:%d\n",getpid());


        pid_t return_pid = fork();

        if(return_pid > 0){
                while(1){
                printf("this father pid:%d return_pid:%d \n",getpid(),return_pid);
                printf("father now num:%d\n",num);
                sleep(1);
                }

        }else if(return_pid == 0){

                printf("this son pid:%d return_pid:%d \n",getpid(),return_pid);
                num += 2;
                printf("child now num:%d\n",num);
                exit(6);
        }
}

//vfork创建子进程
pid_t vfork(void);
//注意fork开辟的子进程,会等待子进程执行完并exit(num)后,父子进程才继续执行,
//【子进程不会成为僵尸进程】;
//例:

#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
        pid_t pid;
        pid = getpid();
        printf("this pid:%d\n",getpid());
        int num = 0;
        printf("start_father_num:%d \n",num);
        pid_t return_pid = vfork();
        if(return_pid > 0){
                while(1){
                        printf("this father pid:%d return_pid:%d \n",getpid(),return_pid);
                        printf("num = %d\n",num);
                        sleep(1);
                }
        }
        else if(return_pid == 0){
                int i;
                for(i=0;i<3;i++){
                        printf("this son pid:%d return_pid:%d \n",getpid(),return_pid);
                        num++;
                        sleep(1);
                }
                exit(0);
        }
        return 0;
}

exit(6);            wait(status);   WEXITSTATUS(status); 

子进程退出;  等待子进程; 获取子进程退出状态码;

//wait() 返回的是子进程的ID 即pid;
//里面的 int *status 是子进程的exit(num)的num码;
//后续使用WEXITSTATUS(status),即可打印出来子进程退出时的状态码;
pid_t wait(int *status);
//例:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
        pid_t pid;
        int status = 0;
        pid = getpid();
        printf("start father pid:%d\n",getpid());
        pid_t return_pid = fork();
        if(return_pid > 0 ){
                pid_t child_pid = wait(&status);
                printf("\n\nwait_return_childe_pid:%d\n",child_pid);
                printf("child exit code:%d \n",WEXITSTATUS(status));
                while(1){
                printf("this father pid:%d fork_return_pid:%d > 0  \n",getpid(),return_pid);
                sleep(1);
                }
                }else if(return_pid == 0){
                        int i;
                        for(i=0;i<3;i++){
                                printf("this son pid:%d fork_return_pid:%d == 0 \n",getpid(),return_pid);
                        }
                        exit (6);
                }



        return 0;
}

exec组函数 对比 system + popen :(程序/进程跳转)

大佬精彩博文: https://blog.csdn.net/u014530704/article/details/73848573

观后感:

跟着execl/execlp指定的程序跑了,不回来了!

    //  date 获取时间的程序
    execl("./PATH","date","NULL");
    //  execl(程序所在路径,程序名,结尾必须为NULL)
    //  就像这样用,在当前程序运行到这句代码时,
    //  便将替换为后续执行execl所指的程序,不带回头的那种!

    execlp("date","date",NULL);
    //  execlp(程序名,程序名,结尾必须为NULL)
    //  就像这样用,它带p,能自己在环境变量下搜索对应的程序并替换后续执行;
    //  也是不带回头的那种!

相比较之下 system 执行完指定程序后,还会回来,挺好!

    system("cat demo1.c");
    //执行完成后返回原程序,继续执行后续代码;

而对比popen 而言,popen除了将指定程序/代码执行完之后,继续执行后续代码外,还将读/写的内容放在管道内,并以文件指针的形式返回;

#include <stdio.h>
#include <unistd.h>
int main()
{
        printf("------------------------------------------------\nPS:\n");

        char* p = "ps";
        FILE *fd = popen(p,"r");
        char data[1024];
        fread(&data,1024,1,fd);
        printf("%s\n",data);
        perror("why");
        return 0;
}

进程间通讯:

int pipe(int pipefd[2]);  (无名管道,在文件里看不到) 

里面的fd[2]数组,其中 fd[0] : 读的fd, fd[1] : 写的fd;

例:通过在父子进程中 close  (fd[0]/fd[1])  配合read(); write(); 实现进程间通讯;

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
        printf("------------------------------------------------:\n");
        int fd[2];
        int n_pipe = pipe(fd);

        char data1[128];
        if(n_pipe < 0){
                printf("error: can not creat pipe!\n");
                perror("why");
        }

        int pid = fork();
        if(pid < 0){
                printf("error: creat child failed!\n");
                perror("why");
        }
        if(pid > 0){
                // sleep(2);
                printf("this is father pc\n");
                close(fd[0]);
                write(fd[1],"hello pipe from father;",strlen("hello pipe from father;"));
                close(fd[1]);
        }
        if(pid == 0){
                printf("this is child pc\n");
                close(fd[1]);
                read(fd[0],data1,128);
                printf("data : %s\n",data1);
                exit(9);
                }
        return 0;
}

打印: 

mkfifo创建有名管道文件;成功返回0;失败返回-1并设置erron = -1;

返回值判断报错值:EEXIST,可以锁定报错为文件已存在目录中;

/*
int mkfifo(const char *pathname, mode_t mode);
RETURN VALUE
    On success mkfifo() and mkfifoat() return 0.  In the  case  of
    an  error,  -1 is returned (in which case, errno is set appro‐
    priately).
    EEXIST pathname already exists.  This includes the case  where
    pathname is a symbolic link, dangling or not.
*/

//例:
#include<stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
int main()
{
        if(mkfifo("./demo1.txt",0666) < 0 && errno == EEXIST ){
        printf("mkfifo error:\n");
        perror("why");
    }
    return 0;
}

mkfifo() 有名管道(会生成临时文件);  配合 open(); read(); write(); 实现进程间通讯;

例 mkread +  mkwrite:

//demo mkread:
#include<stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
int main()
{
        char buf[30]={0};
        int nff = mkfifo("./demo10.txt",0600);
        if(nff < 0 || errno == EEXIST ){
                printf("mkfifo error:\n");
                perror("why");
        }
        if(nff == 0){
                printf("mkfifo OK! \n");
        }
        int fd = open("./demo10.txt",O_RDONLY);
        printf("open success\n");

        int n_read = read(fd,buf,30);
        printf("read %d byte frome fifo context:\n%s\n",n_read,buf);

        int n_sys = system("rm ./demo10.txt");
        if(n_sys < 0 || n_sys ==127 ){
                printf("./demo10.txt delect error! \n");
                perror("why");
        }else{
                printf("\n--------------------------------------------");
                printf("\nsystem: ./demo10.txt delect success !\n");
                printf("--------------------------------------------\n");

        }

        close(fd);
        return 0;
}
//demo mkwrite:
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
int main()
{
        char buf[30]={"hello mkfifo file_read/write"};

        int fd = open("./demo10.txt",O_WRONLY);
        printf("open success\n");

        int n_write = write(fd,buf,strlen(buf));
        printf("write %d byte give fifo context:\n%s\n",n_write,buf);

        close(fd);
        return 0;
}

打印: 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1139071.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

大数据Flink(一百零三):SQL 表值聚合函数(Table Aggregate Function)

文章目录 SQL 表值聚合函数(Table Aggregate Function) SQL 表值聚合函数(Table Aggregate Function) Python UDTAF,即 Python TableAggregateFunction。Python UDTAF 用来针对一组数据进行聚合运算,比如同一个 window 下的多条数据、或者同一个 key 下的多条数据等,与…

【micro ros】快速上手:在 RT-Thread上运行 micro ros

文章目录 快速上手micro ros && RT-Thread&#xff08;serial和udp方式&#xff09;1.背景介绍2.工程准备工作2.1 克隆 RT-Thread主仓2.2 克隆 env-windows 3.编译准备工作3.1 python & cmake安装3.2 scons工具安装3.3 GNU make安装3.4 Fastgithub安装 4.工程配置4…

[SQL开发笔记]LIKE操作符:在 WHERE 子句中搜索列中的指定模式

一、功能描述&#xff1a; LIKE操作符&#xff1a;用于在 WHERE 子句中搜索列中的指定模式。 二、LIKE操作符语法详解&#xff1a; LIKE 语法 SELECT column1, column2,…FROM table_nameWHERE column LIKE pattern; 参数说明&#xff1a; &#xff08;1&#xff09;colum…

全球生物气候产品2.5m和30s分辨率

简介 生物气候是指生物和气候相互作用的结果&#xff0c;包括植物和动物对气候的影响&#xff0c;以及气候对生物的影响。生物气候研究的是生物、气候、土地和水等自然要素之间相互作用的过程&#xff0c;旨在探讨它们是如何互动并导致生态系统的变化的。生物气候对于理解全球…

C#,数值计算——分类与推理,基座向量机(SVM,Support Vector Machines)的计算方法与源程序

把 Support Vector Machines 翻译成 支持向量机 是书呆子翻译。基座向量机 不好吗。 1 文本格式 using System; namespace Legalsoft.Truffer { /// <summary> /// Support Vector Machines /// </summary> public class Svm { priv…

上海亚商投顾:沪指震荡反弹 华为汽车、卫星通信板块再度爆发

上海亚商投顾前言&#xff1a;无惧大盘涨跌&#xff0c;解密龙虎榜资金&#xff0c;跟踪一线游资和机构资金动向&#xff0c;识别短期热点和强势个股。 一、市场情绪 三大指数早盘低开低走&#xff0c;深成指、创业板指一度跌超1%&#xff0c;午后集体拉升翻红。 华为汽车概念…

KMS在腾讯云的微服务实践助力其降本50%

背景介绍 KMS 是一家日本的游戏公司&#xff0c;主要经营游戏业务、数字漫画业务、广告业务、云解决方案业务等&#xff0c;出品了多款在日本畅销的漫画风游戏&#xff0c;同时有网络漫画专业厂牌&#xff0c;以内容创作为目标&#xff0c;拥有原创 IP 创作、游戏开发等多元化发…

WSL2Linux 子系统(六)

WSL 连接USB WSL (Windows Subsystem for Linux) 是一种在 Windows 操作系统上运行 Linux 应用程序的兼容层。它的主要作用是提供了一个类似于虚拟机的环境&#xff0c;使得在 Windows 上开发和运行基于 Linux 的应用变得更加方便。然而&#xff0c;WSL 目前还不支持直接通过 …

spring6-提前编译:AOT

提前编译&#xff1a;AOT 1、AOT概述1.1、JIT与AOT的区别1.2、Graalvm1.3、Native Image 2、演示Native Image构建过程2.1、GraalVM安装&#xff08;1&#xff09;下载GraalVM&#xff08;2&#xff09;配置环境变量&#xff08;3&#xff09;安装native-image插件 2.2、安装C的…

【Unity程序技巧】事件管理器

&#x1f468;‍&#x1f4bb;个人主页&#xff1a;元宇宙-秩沅 &#x1f468;‍&#x1f4bb; hallo 欢迎 点赞&#x1f44d; 收藏⭐ 留言&#x1f4dd; 加关注✅! &#x1f468;‍&#x1f4bb; 本文由 秩沅 原创 &#x1f468;‍&#x1f4bb; 收录于专栏&#xff1a;Uni…

TIA博途_Profinet通信故障诊断及常见错误解决方法汇总

TIA博途_Profinet通信故障诊断及常见错误解决方法汇总 1. 在线诊断报硬件组件的用户数据错误,设备组态不支持 解决方法: (1)检查模块终端盖板; (2)检查组态模块与实际组装模块顺序型号是否一致。 2. 网络视图,设备视图界面显示黑色感叹号 解决方法: PLC转离线,下载硬…

疫情物资管理系统-基于SSM实现

包括-源码参考文档 下载地址: https://juzhendongli.store/commodity/details/5

Spark UI中Shuffle dataSize 和shuffle bytes written 指标区别

背景 本文基于Spark 3.1.1 目前在做一些知识回顾的时候&#xff0c;发现了一些很有意思的事情&#xff0c;就是Spark UI中ShuffleExchangeExec 的dataSize和shuffle bytes written指标是不一样的&#xff0c; 那么在AQE阶段的时候&#xff0c;是以哪个指标来作为每个Task分区大…

【计网 CDN】计算机网络 CDN(Content Delivery Network)分布式网络架构详解:中科大郑烇老师笔记 (八)

目录 0 引言1 为什么需要分布式的网络架构&#xff1f;2 视频流化服务2.1 多媒体&#xff1a;视频2.2 存储视频的流化&#xff08;Streaming&#xff09;服务2.3 流媒体传输协议&#xff1a;DASH2.4 面临挑战&#xff1a;服务器如何向上百万用户同时提供视频流化内容&#xff1…

buuctf_练[GYCTF2020]FlaskApp

[GYCTF2020]FlaskApp 文章目录 [GYCTF2020]FlaskApp常用绕过方法掌握知识解题思路解题一 -- 计算pin码解题二 -- 拼接绕过 执行命令 关键paylaod 常用绕过方法 ssti详解与例题以及绕过payload大全_ssti绕过空格_HoAd’s blog的博客-CSDN博客 CTF 对SSTI的一些总结 - FreeBuf网…

Java中会出现内存泄漏吗

这是一个老生常谈的面试题&#xff0c;本文就系统讲解一下吧 虽然Java有GC垃圾⾃动回收功能&#xff0c;但并不是说Java程序就不会内存泄漏。如果一个对象没有地⽅会使⽤到&#xff0c;但是却仍然有引用指向他&#xff0c;那么垃圾回收器就无法回收他&#xff0c;这种情况就属于…

重复性管理--抽象的重要性(下)

接着 上一篇的谈论, 继续谈论抽象在重复性管理中的重要作用. 好的抽象与糟糕的抽象? 通过前面的一些例子, 你可能形成了一个印象: 所谓抽象很多时候就是把一些代码封装到一个方法中. 不过事实上并不是这么简单的. 抽象的结果确实很多时候产生了一个方法, 但不是说我把一堆代…

05 网络和防火墙等其他

网络和其他 ifconfig : 主机ip地址查询

从过去到未来:回顾DDR技术的演进和未来趋势

DDR技术作为内存的核心&#xff0c;其性能的飞速发展直接推动着计算机的计算能力。 本文将简明扼要地介绍DDR技术的发展历程。 一、SDR时代 20世纪90年代&#xff0c;Intel公司推出了首款同步动态随机存储器SDR SDRAM。其采用时钟同步接口&#xff0c;时钟频率典型为66MHz或8…

【洛谷算法题】P2433-小学数学 N 合一【入门2分支结构】

&#x1f468;‍&#x1f4bb;博客主页&#xff1a;花无缺 欢迎 点赞&#x1f44d; 收藏⭐ 留言&#x1f4dd; 加关注✅! 本文由 花无缺 原创 收录于专栏 【洛谷算法题】 文章目录 【洛谷算法题】P2433-小学数学 N 合一【入门2分支结构】&#x1f30f;题目描述&#x1f319;问题…