Linuc C 编程实例1

1 get.c

#include <stdio.h>
#include <string.h>
#include <strings.h>

int main(void)
{
        char buf[100];
        bzero(buf, 100);

        fgets(buf, 100, stdin);

        printf("you have input %d letters\n", strlen(buf));

        return 0;
}

bzero函数
原型:extern void bzero(void *s, int n); 
用法:#include <string.h> 
功能:置字节字符串s的前n个字节为零。 
bzero无返回值。

    这和Windows不一样; 

2 fork1.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
 
int global = 22;
 
int main(void)
{
	int test = 0,stat;
	pid_t pid;
 
	pid = fork();
 
	if(pid < 0)
	{
		perror("fork");
		return -1;
	}
	else if(pid == 0)
		{
			global++;
			test++;
			printf("global = %d test = %d Child,my PID is %d\n",global,test,getpid());
			exit(0);
		}
		else
		{
			global += 2;
			test += 2;
			printf("global = %d test = %d Parent,my PID is %d\n",global,test,getpid());
			exit(0);
		}
}

 fork函数的返回情况是,

pid_t pid=fork();
    if(pid==0){  //子进程
    }
    if(pid>0){//父进程
    }
    if(pid<0){//出错
    }

3 exev.c

#include <stdio.h>
#include <unistd.h>
 
int main()
{
	if(execlp("ps","ps","-ef",NULL) < 0)
	{
		perror("execlp error");
		return -1;
	}
 
	return 0;
}

   Linux 中有6个以 exec 开头的函数,

#include <stdio.h>
函数原型    
int execl (const char *path,const char *arg,...);
int execv (const char *path, char *const argv[]);
int execle (const char *path,const char *arg,....,char *const envp[]);
int execve(const char *path, char  const *argv[],char *const envp[]);
int execlp (const char *file,const char *arg,...);
int execvp (const char *file, char *const argv[]);

函数返回值    -1;出错

exec 函数族可以默认使用系统的环境变量,也可以传入指定的环境变量,这里,以"e" (Enviromen) 结尾的两个函数execle 、execve 就可以在 envp[] 中传递当前进程所使用的环境变量;

4 ftest1.c

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char const *argv[]) {

    int fd = -1; //文件描述符

    //打开文件
    fd = open( "mytest.txt", O_RDWR );

    if ( -1 == fd ) {
        printf("文件打开失败\n");
    }else {
        printf("文件打开成功,fd=%d\n", fd );
    }

    //读取文件
    int count = 0;
    char buf[20];
    count = read( fd, buf, 50 );
    if ( -1 == count ) {
        printf("文件读取失败\n");
    }else {
        printf("文件读取成功,实际读取的字节数目为:%d\n内容为%s\n", count, buf );
    }

    //关闭文件
    close( fd );

    return 0;
}

    文件操作;文件要先存在; 

运行情况如下;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值