RSS

Implementation of certain UNIX Commands

07 Mar
There are the following programs in this post:
  • Cat command
  • Copy command
  • ls|sort
  • wc
  • wc file1 file2
  • ls|sort|wc
“cat” command:- Used to write/create a file(cat>file1) and to display its contents(cat file1)
#include<stdio.h>
#include<fcntl.h>
main(int argc, char** argv)
{
int i,n,fd1,fd2;
char buff[1024];
if(argc==1)
{
fd1=open(“newfile”,O_CREAT|O_WRONLY,0644);
while((n=read(1,buff,1024))>0)
{
write(fd1,buff,n);
}
close(fd1);
}
else
for(i=1;i<=argc;i++)
{
fd1=open(argv[i],O_RDONLY);
while((n=read(fd1,buff,1024))>0)
{
write(1,buff,n);
}
close(fd1);
}
“copy” command:- Used to copy contents of one file to another (cp file1 file 2)
#include<stdio.h>
#include<fcntl.h>
main(int argc, char **argv)
{
int n,fd1,fd2;
char buff[1024];
fd1=open(argv[1],O_RDONLY);
fd2=open(argv[2],O_CREAT|O_WRONLY,0644);
while((n=read(fd1,buff,1024))>0)
{
write(fd2,buff,n);
}
close(fd1);
close(fd2);
}
“ls|sort” command:- Used to list all files and directories in sorted order
#include<stdio.h>
main()
{
int pfd[2];
pipe(pfd);
int id=fork();
if(id==0)
{
close(1);
dup(pfd[1]);
close(pfd[0]);
close(pfd[1]);
execlp(“ls”,”ls”,0);
}
else
{
close(0);
dup(pfd[0]);
close(pfd[0]);
close(pfd[1]);
execlp(“sort”,”sort”,0);
}
}
“wc” command:-
#include<stdio.h>
#include<fcntl.h>
int main(int argc,char *argv[])
{
int id,fd,i;
id=fork();
if(id==0)
{
if(argc>1)
{
execvp(“wc”,argv);
exit(0);
}
}
else
wait();
return 0;
}
“wc f1 f2” command:-
#include<stdio.h>
#include<fcntl.h>
main()
{
int id,fd1;
id=fork();
if(id==0)
{
fd1=open(“f3”,O_CREAT|O_WRONLY,0644);
close(1);
dup(fd1);
execlp(“wc”,”wc”,”f1″,0);
}
else
wait();
}
“ls|sort|wc” command:-
#include<stdio.h>
#include<fcntl.h>
#include<stdlib.h>
int main()
{
int pfd1[2],pfd2[2],chid,chid2;
pipe(pfd1);
chid=fork();
if(chid==0)
{
pipe(pfd2);
chid2=fork();
if(chid2==0)
{
//ls process or inner child process
close(pfd2[0]);
close(1);
dup(pfd2[1]);
close(pfd2[1]);
close(pfd1[0]);
close(pfd1[1]);
execlp(“ls”,”ls”,0);
exit(0);
}
else
{
close(pfd2[1]);
close(0);
dup(pfd2[0]);
close(pfd2[0]);
printf(“the flag”);
close(1);
dup(pfd1[1]);
close(pfd1[1]);
close(pfd1[0]);
execlp(“sort”,”sort”,0);
waitpid(chid2,NULL,0);
exit(0);
}
}
else
{
close(pfd1[1]);
close(0);
dup(pfd1[0]);
close(pfd1[0]);
execlp(“wc”,”wc”,0);
waitpid(chid,NULL,0);
exit(0);
}
return 0;
}
Advertisements
 
Leave a comment

Posted by on March 7, 2011 in Unix/Linux

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: