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;
}
文件操作;文件要先存在;
运行情况如下;