$ ./myecho x x $ ./myecho a b c a b c
#include <stdio.h>
int main(int argc, char *argv[])
{
if(argc < 2){
printf("lack of argurments");
return -1;
}
printf("%s\n", argv[1]);
return 0;
}
第二种方法:使用execl(或execv)函数调用echo命令
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int argc, char *argv[]){
if(argc < 2){
printf("lack of argurments");
return -1;
}
pid_t pid;
pid = fork();
if(pid == 0){
execl("/bin/echo", "echo", argv[1], NULL);
}
wait(NULL);
return 0;
}
$ cat /etc/passwd root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin bin:x:2:2:bin:/bin:/usr/sbin/nologin ... $ ./mycat /etc/passwd root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin bin:x:2:2:bin:/bin:/usr/sbin/nologin ...
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#define MAXSIZE 65535
int main(int argc, char *argv[])
{
if(argc < 2){
printf("lack of argurments");
return -1;
}
int fd;
fd = open(argv[1], O_RDONLY);
if(fd < 0){
printf("open file failure\n");
return -1;
}
char str[MAXSIZE];
int count = read(fd, str, MAXSIZE - 1);
while(count > 0){
printf("%s\n", str);
memset(str, '\0', MAXSIZE);
count = read(fd, str, MAXSIZE - 1);
}
close(fd);
return 0;
}
第二种方法
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int argc, char *argv[]){
if(argc < 2){
printf("lack of argurments");
return -1;
}
pid_t pid;
pid = fork();
if(pid == 0){
execl("/bin/cat", "cat", argv[1], NULL);
}
wait(NULL);
return 0;
}
$ cat /etc/passwd root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin bin:x:2:2:bin:/bin:/usr/sbin/nologin ... $ ./mycp /etc/passwd passwd.bak $ cat passwd.bak root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin bin:x:2:2:bin:/bin:/usr/sbin/nologin ...
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#define MAXSIZE 65535
int main(int argc, char *argv[])
{
if(argc < 3){
printf("lack of argurments");
return -1;
}
int inFd, outFd;
inFd = open(argv[1], O_RDONLY);
outFd = open(argv[2], O_WRONLY | O_TRUNC | O_CREAT);
if(inFd < 0){
printf("open inFile failure\n");
return -1;
}
if(outFd < 0){
printf("open outFile failure\n");
return -1;
}
char str[MAXSIZE];
int count = read(inFd, str, MAXSIZE - 1);
while(count > 0){
write(outFd, str, strlen(str));
memset(str, '\0', MAXSIZE);
count = read(inFd, str, MAXSIZE - 1);
}
close(inFd);close(outFd);
return 0;
}
第二种方法
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int argc, char *argv[]){
if(argc < 3){
printf("lack of argurments");
return -1;
}
pid_t pid;
pid = fork();
if(pid == 0){
execl("/bin/cp", "cp", argv[1], argv[2], NULL);
}
wait(NULL);
return 0;
}