Archive for the ‘Uncategorized’ Category

PROCESSES IN LINUX

April 22, 2008

Write a program which creates a child process, waits for the termination of its child and lists its PID, together with the state in which the process was terminated (in decimal and hexadecimal).

#include <stdio.h>
#include <signal.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
int pid, state;
printf(“before the fork\n”);

if ((pid =fork() != 0))
{
printf(“parent\n”);
wait(&state);
}
else
{
printf(“child\n”);
execl(“./child”, “child”, 0);
perror(“Error exec”);
}
printf(“after fork state = %d\n”,state);
printf(“PID child = %d terminated\n”, pid);
}

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

printf(“child begins\n”);
pid = getpid();
printf(“child %d ends\n”, pid);

exit(10);
return 1;
}

Write a program which receives from the keyboard the names of some Linux commands without parameters and then executes them. The system call execlp should be used. When waiting for the input of a command, the program should list the prompter ’>’.

#include<sys/types.h>
#include<sys/wait.h>
#include <stdio.h>
#include <unistd.h>

int main(void)
{
char buf[10];
pid_t pid;
int status;

printf(“>”);
while (fgets(buf, 10, stdin) != NULL)
{
buf[strlen(buf)-1] = 0;
if ( (pid = fork()) < 0)
{
perror(“The error fork”);
exit(1);
}
else if (pid == 0)
{
execlp(buf, buf, 0);
perror(“The error exec”);
exit(2);
}
if (( pid = waitpid(pid, &status, 0)) < 0)
{
perror(“the error waitpid”);
exit(2);
}
printf(“> “);
}
exit(0);

}

#include<sys/types.h>
#include<sys/wait.h>
#include <stdio.h>
#include <unistd.h>

int main()
{
int pid, k=7,stat;
pid =fork();
wait(&stat);
printf(” %d returned\n”, pid);
if (pid) k=2;
printf(“k=%d\n”, k);
sleep(5);
printf(“gata bidiu”);
}

Execute the program below on test files with increasing sizes (up to some MB) and explain the result.

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int fdR, fdW;
char c;

void rd_wr()
{
for (;;)
{
if (read( fdR, &c, 1) != 1) return;
write( fdW, &c, 1);
}
}

int main(int argc, char * argv[])
{
if (argc != 3) exit(1); //verify if there are enough arguments

if ((fdR=open( argv[1], O_RDONLY)) < 0) { //open the file of the first argument -read
perror(“The error open”);
exit(1);
}
if ((fdW=creat(argv[2], 0600)) < 0) { //create the file of the second argument – write
perror(“The error create”);
exit(1);
}
fork(); //create new process

rd_wr();
exit(0);
}

Write a C program in order to show how the children of a terminated parent process automatically become the children of the init process.
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>

int main( void)
{
int pid;
pid= fork();
printf(“the curent processes %d and the parents %d \n”, getpid(), getppid());

if (pid != 0)
exit(0);
else
{
//execl;
sleep(1);
printf(“the curent processes %d and the parents %d \n”, getpid(), getppid());

}
}

Write a C program which creates a process in the zombie state.
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>

int main( void)
{
int pid;
pid= fork();

if (pid == 0) //we are in the child
exit(0);
sleep(1);
execlp(“ps”, “ps”, “-la”, NULL);
}
//primul parametru e calea, doar apoi avem ce ne apare in linia de comanda

Write a C program which shows how two processes which are members of the relationship parent-child: are concurrent from the execution’s point of view, initially the child is a copy of the parent, but every process has its own data.

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

int main( void)
{
int pid;
int n=0;
int status;

pid= fork();
while (n<10)
{
if (pid == 0)
{
//we are in the child
printf(“this is the son working: %d\n”, n);
n = n + 2;
sleep(1);
}
else
{
//we are in the parent
//    wait(&status);
printf(“this is the parent working: %d\n”, n);
n = n +3;
sleep(1);
}
}

}

Write two C programs: one called client.c, the other called server.c. The client program lists a prompter and reads from the keyboard two integers and one of the characters ’+’ or ’–’. The read information is transmitted with the help of the system call execl to a child process, which executes the server’s code. After the child (server) process finishes the operation, it transmits the result to the parent process (client) with the help of the system call exit. The client process prints the result on the screen and also reprints the prompter, ready for a new reading.

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

int main()
{
int pid;
char op1, op2;
char sign;
int status;

printf(“>”);
scanf(“%c %c %c”, &op1, &sign, &op2);

pid = fork();

if (pid == 0)
{
if (execl(“./child.exe”, &op1, &op2, &sign, NULL)<0)
perror(“eroare”);
}
else if (pid>0)
{
waitpid(pid, &status, 0);
printf(“result %d\n”, WEXITSTATUS(status));

}

exit(0);

}

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

int main( int argc, char **argv)
{
int a;
int b;
int res=0;

a = *argv[0] – 48;
b = *argv[1] – 48;

printf (“\n %d %d “, a, b );

if ( *argv[2] == ‘+’)
res = a+b;
else res = a-b;

return res;
}

Threads in Linux

April 22, 2008

rite a program that tests whether the threads of a process are executed concurrently or not. The created threads should call a function that contains an infinite loop that prints out the ID of the thread and the ID of the process to which the thread belongs to.

#include <pthread.h>
#include <stdio.h>

void* thFunction(void* arg)
{
int* val = (int*) arg;
int id = pthread_self();

int i;
for (i =0; i<5; i++)
{
printf(“Thread with id %d\n”, id);
sleep(2);
}
}

int main()
{
pthread_t th1;
pthread_t th2;
pthread_t th3;

int arg1 = 1;
int arg2 = 1;
int arg3 = 1;

int id = pthread_self();
printf(“Main thread with id %d\n”, id);
pthread_create(&th1, NULL, thFunction, &arg1);
pthread_create(&th2, NULL, thFunction, &arg2);
pthread_create(&th3, NULL, thFunction, &arg3);

pthread_join(th1, NULL);
pthread_join(th3, NULL);
pthread_join(th2, NULL);

return 0;
}

Using the program written for the previous problem, test the two different reactions of a thread to a cancel request coming from another thread through the call of the pthread_cancel function.

#include <pthread.h>
#include <stdio.h>

void* thFunction(void* arg)
{
int* val = (int*) arg;
int id = pthread_self();

pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);

int i;
for (i =0; i<5; i++)
{
printf(“Thread with id %d\n”, *val);
sleep(1);
}
}
int main()
{
pthread_t th1;
pthread_t th2;
pthread_t th3;

int arg1 = 1;
int arg2 = 2;
int arg3 = 3;

int id = pthread_self();
printf(“Main thread with id %d\n”, id);
pthread_create(&th1, NULL, thFunction, &arg1);
pthread_create(&th2, NULL, thFunction, &arg2);
pthread_create(&th3, NULL, thFunction, &arg3);

pthread_cancel(th1);

pthread_join(th1, NULL);
pthread_join(th3, NULL);
pthread_join(th2, NULL);

return 0;
}

Write a program that specifies the maximum number of threads that can simultaneously exist in the same process. To avoid overloading the processor, the created threads will call the function sleep inside an infinite loop. To find the wanted number, the value returned by the pthread_create function is tested, so to detect the moment when no more threads can be created.

#include <pthread.h>
#include <stdio.h>

void* thFunction(int arg)
{
printf(“%d\n”,arg);
sleep(100);
}

int main()
{
int count =0;
pthread_t th1;
int arg1 = 1;
while (1) //thread successfuly created
{
arg1++;
printf(“-%d\n”,arg1);
if (pthread_create(&th1, NULL, thFunction, arg1) == 0)
count++;
else
{
printf(“the maximum number is %d\n”, count);
return 0;
}

}
return 0;
}

Write a server type C program that periodically creates threads that simulate the handling of some requests from clients. The server threads display a message, wait for a while (using sleep function) and then terminate. In the same time, the server also accepts commands introduced from keyboard. Implement the stop command of the server, like when a special key is pressed (for example ‘x’): the process should not create new threads and end. But ending the process should be done in a clean state, only after the termination of the existing threads at that time.

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

int a = 1;

void* test()
{
char ch;
scanf(“%c”,&ch);
if(ch==’\n’)
a = 0;
else
a = 1;
}

void* thFunction(void* arg)
{
int i;
printf(“new client request\n”);
pthread_t th;
a = 1;
for ( i= 0; i<3; i++)
{
printf(“the thread is at the second %d\n”, i);
pthread_create(&th, NULL, test, &i);
sleep(1);
pthread_cancel(th);
if(a==0)
return 0;
}
}

int main()
{
int count =0;
pthread_t th1[50];
int arg1 = 1;
char ch;
int* state[30];
int i=0;

while (1)
{
printf(“enter x for terminating the process.”);
scanf(“%c”, &ch);
if (ch != ‘x’)
{
scanf(“%c”, &ch);
arg1++;
if (pthread_create(&th1[i], NULL, thFunction, &arg1) != 0) //thread unsuccessfuly created
return 0;

pthread_join(th1[i], NULL);
i++;
}
else
{
printf(“\nchar =%c\n”, ch);
exit(0);
}
}

return 0;
}

Modify Problem 4, such that the threads that simulate the handling of the client requests to execute in an infinite loop intensive computational operations (for example calculating the first N prime numbers or just doing “nothing”). When a key is pressed, the server has to display the number of threads created till that moment. Follow how the computational threads influence the reaction time of the thread that reads from the keyboard (the interactive one).

#include <pthread.h>
#include <stdio.h>

int count = 0;
int a;
char ch = ‘a’;

void* thFunction(void* arg)
{
sleep(10);
//count–;
}

void* test()
{
char ch1;
scanf(“%c”,&ch);
if(ch==’x')
a = 0;
else
a = 1;

}

int main()
{
pthread_t th1;
int arg1 = 1;
printf(“enter x for terminating the process.\n”);
while (1) //thread successfuly created
{
a = 1;

if( pthread_create(&th1, NULL, test, &a) !=0 )
{
printf(“stack full ( at %d ), cannot read key\n”,count);
a = 0;
}
else
{
sleep(1);
pthread_cancel(th1);
}

if(ch == ‘l’)
printf(“the number is %d\n”, count);
if (a)
{
arg1++;
int i;
for(i=1;i<100;i++)
if (pthread_create(&th1, NULL, thFunction, &arg1) == 0)
count++;
}
else
return 0;
}
return 0;
}

Test the behavior of different threads of the same process that simultaneously access functions that read from the keyboard.
#include <pthread.h>
#include <stdio.h>

void* thFunction(void* arg)
{
int number;
int id = pthread_self();

int i;

printf(“Thread with id %d\n”, id);
printf(“input a number for this thread\n”);
scanf(“%d”, &number);
sleep(2);
printf(“the thread with number %d”, number);

}

int main()
{
pthread_t th1;
pthread_t th2;
pthread_t th3;

int number;
int arg1 = 1;
int arg2 = 1;
int arg3 = 1;

char ch;

int id = pthread_self();
printf(“Main thread with id %d\n”, id);
printf(“\n”, id);

pthread_create(&th1, NULL, thFunction, &arg1);
pthread_create(&th2, NULL, thFunction, &arg2);
pthread_create(&th3, NULL, thFunction, &arg3);

printf(“input a number for the main thread\n”);
scanf(“%d”, &number);
printf(“the theard with number %d\n”, number);

sleep(12);
// pthread_join(th1, NULL);
// pthread_join(th3, NULL);
// pthread_join(th2, NULL);

return 0;
}

Test the effect of the pthread_join function called by the only active thread of a child process, in order to wait till the end of a thread in the parent process, existing there when function fork is called, but not active in the child process. The question is if the active thread will be blocked in the pthread_join or not; if not, what does that function
returns?

#include <pthread.h>
#include <stdio.h>

void* thFunction(void* arg)
{
int* val = (int*) arg;
int id = pthread_self();

printf(“Thread with id %d\n”, id);
sleep(100);

}

int main()
{
int pid;
int arg1=1;
pthread_t th1;
int id = pthread_self();

pthread_create(&th1, NULL, thFunction, &arg1);
printf(“thread created\n”);

pid=fork();
if (pid == 0) //we are in the child process
{
printf(“in the child\n”);
pthread_join(th1, NULL);
printf(“after join\n”);
}
else
if (pid >0) // we are in the parent
{
int j=0;
while(j<5)
{
printf(“in the parent\n”);
j++;
}
exit(0);
}

}

EXAMPLE CANCEL

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

#include <sys/types.h>
#include <unistd.h>

#include <pthread.h>

#define MAXSTEPS 10

char name1[]=”T1″;
char name2[]=”T2″;

void* execThread1(void* threadName)
{
int i;

pthread_setcancelstate(PTHREAD_CANCEL_ENABLE);
for (i=1; i<=MAXSTEPS; i++){
sleep(1);
printf(“Thread %s at step %d\n”, threadName, i);
}

return number;
}

void* execThread1(void* threadName)
{
int i;

pthread_setcancelstate(PTHREAD_CANCEL_DISABLE);
for (i=1; i<=MAXSTEPS; i++){
sleep(1);
printf(“Thread %s at step %d\n”, threadName, i);
}

return number;
}

main()
{

pthread_t t1, t2;

printf(“Starting main thread [%d] with pid=%d\n”, pthread_self(), getpid());

if (pthread_create(&t1, NULL, execThread, name1)<0) {
perror(“Error creating a new thread”);
exit(1);
}

if (pthread_create(&t2, NULL, execThread, name2)<0) {
perror(“Error creating a new thread”);
exit(1);
}

printf(“Main thread created threads [%d, %d]\n”, t1, t2);

pthread_join(t1, NULL);
pthread_join(t2, NULL);

printf(“Thread %s[%d] terminated with state %d\n”, name1, t1, *(state[0]));
printf(“Thread %s[%d] terminated with state %d\n”, name2, t2, *(state[1]));
}

EXAMPLE CLEAN PUSH

#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>

typedef struct m {
int size;
void* pMem;
} MEM;

void allocate_mem(void* arg) {
MEM* p = (MEM*) arg;
p->pMem = malloc(p->size);
if (p->Mem == NULL)
p->size = 0;
printf(“Thread %d has allocated % bytes of memory.\n”, pthread_self(), p->size);
}

void release_mem(void* arg) {
MEM* p = (MEM*) arg;
if (p->pMem)
free(p->pMem);
printf(“Thread %d has released % bytes of memory.\n”, pthread_self(), p->size);
}

void* thFunction(void* arg){
int oldType, i;
MEM  thMem;

pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldType);

thMem.size = 10 * sizeof(int);
thMem.pMem = NULL;

pthread_cleanup_push(release_mem, (void *) &thMem);

allocate_mem(&thMem);

// do some work with the memory
if (thMem != NULL)
for (i=0; i<10; i++) {
thMem.pMem[i] = i;
sleep(1);
}

pthread_cleanup_pop(1);

pthread_setcanceltype(oldType, NULL);
}

main()
{
int i;
pthread_t th[5];

for (i=1; i<=5; i++)
pthread_create(&th[i], NULL, thFunction, NULL);

// cancel the threads
for (i=1; i<=5; i++) {
usleep(100);
pthread_cancel(th[i]);
}

// wait the threads to cancel (finish)
for (i=1; i<=5; i++)
pthread_join(th[i], NULL);
}

EXAMPLE CREATE THREAD

#include <pthread.h>
#include <stdio.h>

void* thFunction(void* arg) {
int* val = (int*) arg;

printf(“Thread with argument %d\n”, *val);
}

main() {
pthread_t th1;
int arg1 = 1;

pthread_create(&th1, NULL, thFunction, &arg1);
pthread_join(th1, NULL);
}

EXAMPLE CREATE JOIN

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

#include <sys/types.h>
#include <unistd.h>

#include <pthread.h>

#define MAXSTEPS 10

char name1[]=”T1″;
char name2[]=”T2″;

void* execThread(void* threadName)
{
int i;
int* number = new int;
char* tmp;

printf(“Starting thread %s [%d] with pid=%d\n”, threadName, pthread_self(), getpid());

for (i=1; i<=MAXSTEPS; i++){
sleep(1);
printf(“Thread %s at step %d\n”, threadName, i);
}

tmp = & ((char*)threadName)[strlen((char*)threadName)-1];
*number = atoi(tmp);

return number;
}

main()
{

pthread_t t1, t2;
int* state[2];

printf(“Starting main thread [%d] with pid=%d\n”, pthread_self(), getpid());

if (pthread_create(&t1, NULL, execThread, name1)<0) {
perror(“Error creating a new thread”);
exit(1);
}

if (pthread_create(&t2, NULL, execThread, name2)<0) {
perror(“Error creating a new thread”);
exit(1);
}

printf(“Main thread created threads [%d, %d]\n”, t1, t2);

pthread_join(t1, (void**) &state[0]);
pthread_join(t2, (void**) &state[1]);

printf(“Thread %s[%d] terminated with state %d\n”, name1, t1, *(state[0]));
printf(“Thread %s[%d] terminated with state %d\n”, name2, t2, *(state[1]));
}

EXAMPLE GETPID GETTHREAD

#include <stdio.h>

#include <sys/types.h>
#include <unistd.h>

#include <pthread.h>

void* execThread(void *arg)
{
printf(“Starting child thread [tid=%d] with [pid=%d]\n”, pthread_self(), getpid());

sleep(2);
}

int main()
{
pthread_t t1;

printf(“Starting process [pid=%d]\n”, getpid());

printf(“Starting main thread [tid=%d] with [pid=%d]\n”, pthread_self(), getpid());

pthread_create(&t1, NULL, execThread, NULL);

printf(“Running main thread [tid=%d] with [pid=%d]\n”, pthread_self(), getpid());

sleep(2);
}

Gnome Proxy Script

April 1, 2008

#! /bin/sh
# Switches the GNOME proxy on/off and can take an optional proxy host+port

usage ()
{
cat << CAT
Usage: `basename $0` on|off|switch [host [port]]
CAT
exit 1
}

[ $# -lt 1 ] && usage

case “$1″ in
“on”)
mode=”manual”
;;
“off”)
mode=”none”
;;
“switch”)
case “`gconftool-2 -g /system/proxy/mode`” in
“none”)
mode=”manual”
;;
“manual”)
mode=”none”
;;
*) # why not turn it off
mode=”none”
;;
esac
;;
*)
usage
;;
esac

gconftool-2 -t string -s /system/proxy/mode “$mode”
[ ! -z "$2" ] && gconftool-2 -t string -s /system/http_proxy/host “$2″ &&
gconftool-2 -t string -s /system/proxy/secure_host “$2″
[ ! -z "$3" ] && gconftool-2 -t int -s /system/http_proxy/port “$3″ &&
gconftool-2 -t int -s /system/proxy/secure_port “$3″

Linux Script Examples 2

April 1, 2008

/*
2.Modify the 1st problem and see whether when creating a file with large holes (hundreds of MB or GB) does the OS allocate space on the HDD for the holes in the file, too, or not. For this you can use the commands stat and df. Find out what value does a read operation return when reading from such a zone.
*/

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

char buf1[]=”LAB “;
char buf2[]=”OS Linux”;

int main( void)
{
int fd;
if ((fd=creat(“file.gol”, 0666)) < 0) {
perror(“Creation error”);
exit (1);
}

if (write(fd, buf1, sizeof(buf1)) < 0) {
perror(“Writing error”);
exit(2);
}

if (lseek(fd, 4096, SEEK_SET) < 0) {
perror(“Positioning error”);
exit(3);
}

if (write(fd, buf2, sizeof(buf2)) < 0) {
perror(“Writing error”);
exit(2);
}
}

/*
4.Write a program that reads the characters located to offset 0, 20, 40, 60 … in an existing text file and appends them to the end of the file. Print out the size of the file before and after all append operations.
*/

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

int main ()
{
int f;

f=open(“test”,O_RDWR);
int flag_read=0;
int lungime_fisier=lseek(f,0,SEEK_END);
char b;
if (f>0)
{
do
{
lseek(f,flag_read,SEEK_SET);
read(f,&b,1);
printf(“\n%d: citim {%c}”,flag_read,b);
lseek(f,0,SEEK_END);
write(f,&b,1);
flag_read+=20;
}
while (flag_read<lungime_fisier);

printf(“\nlungimea fiserului inaite %d si dupa %d”,lungime_fisier,lseek(f,0,SEEK_END));
close(f);
}

return 0;
}

/*
5.Using lseek system call, find out if you can read from and write to any position in a file opened for reading and writing with O_APPEND. Write a program that when you launch N times in the background, writes the ID of the current process in a file. Neither of the programs can continue their execution until all the processes haven’t written their ID in the file. In the end all processes should print out the ID of the following process. Consider N as a known value.
*/

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

int main(int argc,char** argv)
{
int N;
int fd,pid;
int dimi,dima;

printf(“test\n”);
sscanf(argv[0],”%d”,&N);
printf(“N=%d\n”,N);
sscanf(argv[1],”%d”,&fd) ;
printf(“fd=%d”,fd);
pid=getpid();
write(fd,&pid,sizeof(int));
printf(“procesul cu pidul %d si-a scris propriul pid in fisier\n”,pid);
sscanf(argv[2],”%d”,&dimi);
printf(“dimi=%d\n”,dimi);
dima=lseek(fd,0,SEEK_END);
printf(“dima=%d\n”,dima);

while(((dima-dimi)/sizeof(int))<N)
{
sleep(1);
dima=lseek(fd,0,SEEK_END);
}

lseek(fd,dimi,SEEK_SET);

int i=0;
int pidNext;
int val;
while(i<N)
{
read(fd,&val,sizeof(int));
if(val==pid)
{
read(fd,&pidNext,sizeof(int));
lseek(fd,dima,SEEK_SET);
write(fd,&pidNext,sizeof(int));
printf(“procesul cu pidul %d a scris in fisier pidul procesului urm=%d\n”,pid,pidNext);
exit(1);
}
i++;
}
}

/*
6.Write a program that would allow the user to insert a string (read from the standard input) into a file from a certain position. The program call should have the following format: insert file offset string.
*/

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

main( int argc, char *argv[])
{
char buf[100],buf2[100];
char c;
int fd;
int i,j;
int poz,nr,new_poz;

poz = atoi(argv[1]);

j=0;

if (argc != 3)
{
printf(“nu-s bine argumentele\n”);
exit(0);
}

if ((fd=open(argv[2],O_RDWR)) == -1)
{
printf(“Eroare la deschidere fisier”);
exit(1);
}

scanf(“%c”,&c);
i=0;

while(c != ‘.’)
{
buf[i]=c;
scanf(“%c”,&c);
i++;
}

lseek(fd,poz,SEEK_SET);

if ((nr = read(fd,&buf2,sizeof(buf2))) == -1)
{
printf(“Eroare la citire”);
exit(2);
}

lseek(fd,poz,SEEK_SET);

if (write(fd,&buf,i) == -1)
{
printf(“Eroare la scriere”);
exit(3);
}

new_poz=poz+i;

lseek(fd,new_poz,SEEK_SET);

if (write(fd,&buf2,nr) == -1)
{
printf(“Eroare la scriere”);
exit(4);
}
}

/*
7.Consider the program below. Assuming that the file temp exists and that the program is launched in the background explain the result of the following commands:
ls -l temp; df /home; a.out &
$ ls -l temp; df /home;       # după terminarea progr.
$ df /home
*/

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

void main( void)
{
if (open(“temp”, O_RDWR) < 0)
{
perror(“open”);
exit(1);
}

if (unlink(“temp”) < 0)
{
perror(“unlink”);
exit(2);
}

printf(“Unlink done!\n”);

sleep(15);

printf(“END.\n”);

exit(0);
}

/*
8.Write a C program that deletes a directory with all its subfolders. The name of the directory should be read from the command line.
*/

void DeleteDirectory(char *dirName)
{
DIR* directory;
struct dirent *dirEntry;
struct stat inode;
char name[100];

directory = opendir(dirName);
if (directory == 0)
{
printf(“\n***”);
perror(“Error opening the directory.”);
exit(1);
}

while( (dirEntry=readdir(directory)) != 0)
{
sprintf(name, “%s/%s”, dirName, dirEntry->d_name);
lstat(name, &inode);

if(S_ISDIR(inode.st_mode))
{
if(strcmp(dirEntry->d_name, “.”) && strcmp(dirEntry->d_name, “..”) )
{
DeleteDirectory(name);
rmdir(name);
}
}
else if(S_ISREG(inode.st_mode) || S_ISLNK(inode.st_mode))
unlink(name);
else;
}
}

int main(int argc, char **argv)
{
if(argc != 2)
{
printf(“USAGE: %s <directory_name>”, argv[0]);
exit(0);
}

DeleteDirectory(argv[1]);
rmdir(argv[1]);
}

/*
9.Write a program that deletes every 5th byte from a file, but without using a temporary file or allocating a buffer in the memory. For adjusting the size of the file you may use the truncate function.
*/

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

int main(int arg,char** fis)
{
int fd;
int n;
char buf[5];
int ni=0;

fd=open(fis[1],O_RDWR);

if(fd==-1)
{
printf(“Fisierul nu exista”);
exit(2);
}

do
{
if (ni!=0) lseek(fd,ni,SEEK_CUR);
n=read(fd,buf,5);
if (ni!=0)lseek(fd,-ni,SEEK_CUR);
printf(“\n buf:=%s”,buf);

lseek(fd,-5,SEEK_CUR);
printf(“\n scris=%d” , write(fd,&buf,4));
ni++;
}
while(n>=5);

close(fd);
}

/*
10.Write a C program that finds a file in a file-tree starting from a given directory. The name of the file for which we are searching for, as well as the name of the starting directory should be read from the command line. Optionally, the name of the file can be specified as a pattern using the ‘*’ character.
*/

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

void functie(char*dir, char *file)
{
struct dirent* entit;
DIR* director;

director=opendir(dir);

char temp[100];
struct stat statbuf;

printf(“Caut in: %s\n”,dir);

if (director!=0)
{
while ((entit=readdir(director))!=0)
{
strcpy(temp,”");
strcat(temp,dir);
strcat(temp,”/”);
strcat(temp,entit->d_name);
if ((strcmp(entit->d_name,”.”)!=0)&&(strcmp(entit->d_name,”..”)!=0))
functie(temp,file);

}
closedir(director);
}
else
{
lstat(dir,&statbuf);
if (S_ISREG(statbuf.st_mode) && strcmp(basename(dir),file) == 0)
{
int f1 = open(file,O_RDONLY);
int f2 = open(dir,O_RDONLY);
printf(“%d %d”, lseek(f1,0,SEEK_END), lseek(f2,0,SEEK_END));
if( lseek(f1,0,SEEK_END) == lseek(f2,0,SEEK_END)    )
printf(“Am gast fisier: %s\n”, dir);
}
}
}

int main(int argc, char*argv[])
{
functie(argv[1], argv[2]);
return 0;
}

/*
11.Write a C program similar to the previous one, but this time try to find a string in the files.
*/

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

void functie(char*dir, char *string)
{
struct dirent* entit;
DIR* director;

director=opendir(dir);
char temp[100];
struct stat statbuf;
printf(“Caut in: %s\n”,dir);
if (director!=0)
{
while ((entit=readdir(director))!=0)
{
strcpy(temp,”");
strcat(temp,dir);
strcat(temp,”/”);
strcat(temp,entit->d_name);
if ((strcmp(entit->d_name,”.”)!=0)&&(strcmp(entit->d_name,”..”)!=0))
functie(temp,string);

}
closedir(director);
}
else
{
lstat(dir,&statbuf);
if (S_ISREG(statbuf.st_mode) )
{
int f2 = open(dir,O_RDONLY);
int poz = 0;
int len = strlen(string);
char buf[512];
while(read(f2,buf,len) > 0)
{
if(strcmp(buf,string) == 0    )
{
printf(“Am gast in: %s\n”,dir);
break;
}
poz++;
lseek(f2,poz,SEEK_SET);
}

}
}
}

int main(int argc, char*argv[])
{
functie(argv[1], argv[2]);
return 0;
}

/*
12.Write a program having the name move, similar with the Linux command mv. The user should be able to call the program in any of the following ways:
move numeFisOld numeFisNew
move numeFis numeDir
move numeDirOld numeDirNew
*/

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

int main(int argc, char*argv[])
{
execlp(“cp”,”cp”,”-rf”,argv[1],argv[2],0);
execlp(“rm”,”rm”,”-rf”,argv[1],0);
return 0;
}

/*
13.Write a program that would allow traversing a file-tree printing out the type, size and access rights for of the found files. The name of the starting directory should be read from the command line. Observation: be attentive to the symbolic links.
*/

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

void functie(char*dir, char *file)
{
struct dirent* entit;
DIR* director;

director=opendir(dir);
char temp[100];
struct stat statbuf;
if (director!=0)
{
while ((entit=readdir(director))!=0)
{
strcpy(temp,”");
strcat(temp,dir);
strcat(temp,”/”);
strcat(temp,entit->d_name);
if ((strcmp(entit->d_name,”.”)!=0)&&(strcmp(entit->d_name,”..”)!=0))
{
printf(“%s is a directory\n”,entit->d_name);
functie(temp,file);
}
}
closedir(director);
}
else
{
lstat(dir,&statbuf);
if (S_ISREG(statbuf.st_mode))
{
printf(“%s is a regular file, the size of which is %d and has the rights: \n”, dir, statbuf.st_size);
}
else if (s_ISLNK(statbuf.st_mode))
{
printf(“%s is a symbolic link\n”, dir);
}
}
}

int main(int argc, char*argv[])
{
functie(argv[1], argv[2]);
return 0;
}
/*
14.  A binary file fil.bin contains integers. Calculate the arithmetic mean of each group of numbers that are situated between two 0s in the file. Write these obtained values on distinct lines in the file means.txt. The beginning and the end of the file plays the role of a 0, except the case when the first and last element of the file is 0.
*/

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

int N;
int fisBin, n, nrsRead[1000];
void media(int N);
void generateNrs(int N);
FILE *fout;

int main()
{
if ((fisBin=creat(“fis.bin”, 0666)) < 0) {
perror(“Error creating destination file”);
exit(2);
}

N = rand()%1000;
generateNrs(N);
media(N);

}

void media(int N)
{
if ((fisBin=open(“fis.bin”, O_RDWR)) < 0) {
perror(“Error opening source file”);
exit(1);
}

printf(“Media %d”);
int i,n=0,nr = 0;
for (i=0; i<N; i++)
{
if ((n = read(fisBin, &nr, sizeof(int))) < 0)
{
perror(“Error reading file”);
exit(4);
}
else
{
nrsRead[i] = nr;
}
}
close(fisBin);

// calcul

if ((fout = fopen(“fout.txt”,”w”))<0)
{
perror(“Error opening source file”);
exit(1);
}

int sumap = 0, nr_citite = 0, med = 0;
for (i=0; i<N; i++)
{
if ((nrsRead[i] == 0) || (i==N-1))
{
med = sumap/nr_citite;
sumap = 0;
nr_citite = 0;
if ((n=fprintf(fout, “Media %d \n”, med)) < 0)
{
perror(“Error writing destination file”);
exit(4);
}

}
else
{
if ((n=fprintf(fout, ” %d “, nrsRead[i])) < 0)
{
perror(“Error writing destination file”);
exit(4);
}
sumap += nrsRead[i];
nr_citite++;
}
}
}

void generateNrs(int N)
{

if ((fisBin=open(“fis.bin”, O_RDWR)) < 0) {
perror(“Error opening source file”);
exit(1);
}

int i =0,nr;
for (i=0; i<N; i++)
{
nr = rand()%100;
if ((n=write(fisBin, &nr, sizeof(int))) < 0)
{
perror(“Error writing destination file”);
exit(4);
}
else printf(” %d “,nr);
}
printf(“N = %d\n”, N);
close(fisBin);
}

/*
3.Write a C program that writes the lines of a file into another file, but in the reverse order. The names of the files should be read as input parameters.
*/

#include <stdio.h>
#include <stdlib.h>

int main(int argc,char **argv)
{
char **linii;
int nr_linii=0,i;
long lungime_fisier;
FILE *f;

if(argc!=2)
{
printf(“Sintax: %s <filename>\n”,argv[0]);
return 1;
}

if((f=fopen(argv[1],”r”))==NULL)
{
printf(“Error opening the file: <%s>\n”,argv[1]);
return 1;
}

fseek(f,0,SEEK_END);
lungime_fisier=ftell(f);
fseek(f,0,SEEK_SET);

linii=(char **)malloc((nr_linii+1)*sizeof(char *));

while(lungime_fisier>ftell(f))
{
linii[nr_linii]=(char *)malloc(1000 * sizeof(char));
fgets(linii[nr_linii],1000,f);
nr_linii++;
linii=(char **)realloc(linii,(nr_linii+1)*sizeof(char *));
}

for(i=nr_linii-1;i>=0;i–)
{
printf(“%s”,linii[i]);
}

fclose(f);

return 0;
}

/*15.A binary file fil.bin contains numbers and characters in the following way: 2 integers followed by a character from the set {+,-,*,/}. Write a C program that reads a group of numbers and the attached character and performs the operation on the two integers and then writes the result in a file res.txt in the form:
nr1 operator nr2 = result
The result line should be appended to the end of the file. The number of groups in the binary file should be specified in the command line as an input parameter.
*/

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

typedef struct operatie
{
float f1, f2;
char op;
}Op;

int main(int argc, char** argv)
{
int fd, fw;
Op s;
char c;
char buf[8] = “”;
char b[512] = “”;
int i = 0;

if (argc != 3)
{
printf(“UTILIZARE: %s limita1 limita2″, argv[0]);
exit(0);
}

if ((fd = open(“fis.bin”, O_RDONLY)) == -1)
{
perror(“Eroare la deschidere!\n”);
exit(1);
}

if (creat(“rez.txt”, 0666) < 0)
{
perror(“Eroare creare fisier!\n”);
exit(2);
}

if ((fw = open(“rez.txt”, O_WRONLY)) < 0)
{
perror(“Eroare deschidere fisier de iesire!\n”);
exit(3);
}

int nr = 1;            //nr de grupuri

while (read(fd, &c, sizeof(char)) > 0)
{
if (c == ‘ ‘)
{
if (i == 0)
s.f1 = atof(buf);
else
s.f2 = atof(buf);
i++;
strcpy(buf, “”);
}
else
if (c == ‘+’ || c == ‘-’ || c == ‘*’ || c == ‘/’)
{
s.op = c;
if (nr >= atoi(argv[1]) && nr <= atoi(argv[2]))
{
//printf(“\ns.f1 = %f\ns.f2 = %f\ns.op = %c\n”, s.f1, s.f2, s.op);
float interm;
if (s.op == ‘+’)
interm = s.f1 + s.f2;
else
if (s.op == ‘-’)
interm = s.f1 – s.f2;
else
if (s.op == ‘*’)
interm = s.f1 * s.f2;
else
interm = s.f1/s.f2;
sprintf(b, “%s%f %c %f = %f\n”, &b, s.f1, s.op, s.f2, interm);
}
}
else
if (c == ‘\n’)
{
i = 0;
strcpy(buf, “”);
nr++;
}
else
sprintf(buf, “%s%c”, &buf, c);
}

if (write(fw, &b, sizeof(b)) < 0)
{
perror(“Eroare de scriere la iesire!\n”);
exit(4);
}

close(fd);
close(fw);
}

Linux Script Examples

April 1, 2008

echo
echo Directory: “$1″
if test -d “$1″
then
for name in $1/.[a-z,A-Z]* $1/*
do
if test -d “$name”
then
./ls_rec.sh “$name”
elif test -f “$name”
then echo “$name”
fi
done
fi

#3.Write a command file named recho.sh, which displays its arguments in reverse order
#        a.on the same line
#        b.on different lines (the eval command can be used).

echo “The arguments in reverse order, each on a separate line, are:”
for ((i=$#; i>0; i–))
do
eval echo \$$i
done

echo “The arguments in reverse order, all on a single line, are:”
remArgs=$#
while ((remArgs>0))
do
eval echo -n \$$remArgs
((remArgs=$remArgs-1))
done
echo

#  The command file below decides if two directories are identical from the point of view of the content of the files ending in “.c”.

crtdir=`pwd`
if [ -d $1 ]
then
if [ -d $2 ]
then
cd $1
ls -R > $crtdir/f1
cd $crtdir
cd $2
ls -R > $crtdir/f2
cd $crtdir
grep ‘.c$’ f1 > f11       # raman doar fisierele
grep ‘.c$’ f2 > f22       # “.c” ordonat alfabetic
rm f1 f2
if cmp f11 f22
then
echo “Directoarele egale”
else
echo “Directoare diferite”
fi
rm f11 f22
else
echo “$2 nu e director”
fi
else
echo “$1 nu e director”
fi

#5.Write a command file that checks whether two directories are equal, without using the command ls. The names of the two  directories are transmitted #as arguments in the command line. Two directories are considered equal if the trees rooted in them are identical from the point of view of the #structure, and their corresponding nodes have the same name.

dirStructure()
{
if test -d “$1″
then
for name in “$1″/.[a-z,A-Z]* “$1″/*
do
if test -d “$name”
then
basename “$name” >> “$2″
((printDirName++))
dirStructure “$name” “$2″
elif test -f “$name”
then
basename “$name” >> “$2″
fi
done
else echo “First parameter not a directory.”
fi
}

dirStructure $1 tempfile1
dirStructure $2 tempfile2

if cmp tempfile1 tempfile2
then
echo “The directories have the same structure and contain the same files.”
else
echo “The directories have different structure and/or contain different files.”
fi

rm tempfile1 tempfile2

#6.Write a command file that allows the search for a file in the entire structure of a subdirectory, without using the command find or other commands #simillar to it. The arguments are given in the command line.

printAllFilesInDirectory()
{
if test -d “$1″
then
for name in “$1″/.[a-z,A-Z]* “$1″/*
do
if test -d “$name”
then
printAllFilesInDirectory “$name” “$2″
elif test -f “$name”
then
basename “$name” >> “$2″
fi
done
else echo “First parameter not a directory.”
fi
}

printAllFilesInDirectory $1 tempfile
grep $2 tempfile;
if (($?==0))
then
echo “File found!”
else echo “File not found!”
fi
rm tempfile

#7.Write a command file that deletes all C source files from a directory, if their names are found in the structure of another directory. The
#first argument in the command line is the directory where the C source files are located, and the second  is the directory where the search begins.

sourceDirectory()
{
if test -d “$1″
then
for name in “$1″/.[a-z,A-Z]* “$1″/*
do
if test -d “$name”
then
sourceDirectory “$name” “$2″
elif test -f “$name”
then
basename “$name” >> “$2″
fi
done
else echo “First parameter not a directory.”
fi
}

sourceDirectory $1 tempfile

grep ‘.c$’ tempfile > tempfile2

rm tempfile

deleteFiles()
{
file=$1
exec < $file
while read line
do
fileToDelete=`find $2 -name $line`
rm $fileToDelete;
done
}

deleteFiles tempfile2 $2

rm tempfile2

#8.Write a command file that copies the entire structure of a directory as structure in another directory. The two directories are given as arguments in #the command line.

copyDir()
{
cd $1
files=’dir’
for i in $files
do
if test -d $i
then copyDir $i
cd
mkdir
fi
if test -f $i
}

#9.Compute, using the command ls, the number of files and directories in a directory, taking into account the entire structure of the tree rooted in the #given directory. The name of the directory is given as argument in the command line.

filesDirsCount=0

count()
{
cd “$1″
for name in *
do
((filesDirsCount++))
done

for name in *
do
if test -d “$name”
then
count “$name”
fi
done

cd ..
}

count $1
echo “Total number of files and directories: “
echo $filesDirsCount

#10.Write a command file that computes the number of files, directories and symbolic links in a directory, taking into account the entire structure of #the tree rooted in the given directory. Display the same information for all the visited subdirectories. The name of the directory is given in the #command line.

filesCount=0
dirsCount=0
linksCount=0

count()
{
cd “$1″
for name in *
do
if test -d “$name”
then
((dirsCount++))
count “$name”
elif test -f “$name”
then
((filesCount++))
elif test -h “$name”
then
((linksCount++))
fi
done

cd ..
}

count $1
echo “Total number of directories: “
echo $dirsCount
echo “Total number of files: “
echo $filesCount
echo “Total number of symbolic links: “
echo $linksCount

#11.Write a command file that creates a directory whose path is specified as argument in the command line, and in that directory create files named for #the users logged on at that moment.

cd $1
who > tempfile

exec < tempfile
while read line
do
touch “$line”
done

rm tempfile

#12.Write a command file that computes the total number of text lines and the number of words in all the files in a directory, taking into account the #entire structure of the tree rooted in that directory.

linesCount=0
wordsCount=0

count()
{
cd $1
for name in *
do
if test -d “$name”
then
count “$name”
elif test -f “$name”
then
linesInFile=`wc -l < “$name”`
((linesCount+=$linesInFile));

wordsInFile=`wc -w < “$name”`
((wordsCount+=$wordsInFile));
fi
done

cd ..
}

count $1
echo “Total number of lines: “
echo $linesCount
echo “Total number of words: “
echo $wordsCount

#13.Write a command file that executes in a loop the following steps: (1) reads from the keyboard two numbers and an operator +, -, * or /; (2) executes #the desired operation and (3) writes the result on a new line in a file, in the format:
#    Operation_nb: operand1 operator operand2 = result
#The exit from the loop takes place when the character x is introduced on the position of the operator. Before finishing, write the number of executed #operations in the file. The name of the file the results are written to is given as an argument in the command line.

IFS=’ ‘
nrop=0
while read op1 op2 op
do
if test $op1 = ‘x’
then break
fi
nrop=$(($nrop + 1))
rez=$(($op1 $op $op2))
echo $nrop:$op1$op$op2=$rez >> 1
done

Hello world!

April 1, 2008

Welcome to WordPress.com. This is your first post. Edit or delete it and start blogging!