file handling 4

Document Sample
file handling 4 Powered By Docstoc
					System Programming

   Linux Environment
       Lecture # 7
           Linux Environment
❑ Environment variables
❑ Passing arguments to programs
❑ Getting information about the user and the
 host computer
❑ Discovering the limits imposed by the system
           Program Arguments
• int main(int argc, char *argv[])
  – argc is a count of the program arguments
  – argv is an array of character strings representing
    the arguments themselves.
• main()
  – This will still work
  – Default return type is int
  – argc and argv are still there
  – but if you don’t declare them, you can’t use them.
• $ myprog left right ‘and center’
  – the program myprog will start at main with
• argc: 4
• argv: ,“myprog”, “left”, “right”, “and center”-
                  Program arguments
#include <stdio.h>
#include <stdlib.h>                  $ ./args -i -lr ‘hi there’ -f fred.c
int main(int argc, char *argv[])     argument 0: ./args
{                                    option: i
int arg;                             option: lr
                                     argument 3: hi there
for(arg = 0; arg < argc; arg++) {    option: f
if(argv[arg+*0+ == ‘-‘)              argument 5: fred.c
printf(“option: %s\n”, argv[arg]+1);
printf(“argument %d: %s\n”, arg, argv*arg+);
#include <unistd.h>
int getopt(int argc, char *const argv[], const
  char *optstring);
extern char *optarg;
extern int optind, opterr, optopt;
• getopt(argc, argv, “if:lr”);

❑If the option takes a value, that value is pointed to by the
 external variable optarg.
❑ getopt returns -1 when there are no more options to
 process. A special argument, --, will cause getopt to stop
 scanning for options.
❑ getopt returns ? if there is an unrecognized option, which it
 stores in the external variable optopt.
❑ If an option requires a value (such as -f in our example) and
 no value is given, getopt normally returns ?. By placing a
 colon as the first character of the options string, getopt
 returns : instead of ? when no value is given.
#include <stdio.h>                                case ‘:’:
#include <unistd.h>                               printf(“option needs a value\n”);
#include <stdlib.h>                               break;
int main(int argc, char *argv[])                  case ‘?’:
{                                                 printf(“unknown option: %c\n”,
int opt;                                              optopt);
while((opt = getopt(argc, argv, “:if:lr”)) != -   break;
    1) {
switch(opt) {
case ‘i’:
case ‘l’:                                         for(; optind < argc; optind++)
case ‘r’:                                         printf(“argument: %s\n”,
printf(“option: %c\n”, opt);                          argv[optind]);
break;                                            exit(0);
case ‘f’:                                         }
printf(“filename: %s\n”, optarg);                 Now when you run the program, you
               Running getopt
$ ./argopt -i -lr ‘hi there’ -f fred.c -q
option: i
option: l
option: r
filename: fred.c
unknown option: q
argument: hi there
         Environment Variables
• $ echo $HOME
  – /home/username
• putenv and getenv
     #include <stdlib.h>
     char *getenv(const char *name);
     int putenv(const char *string);
              getenv, putenv ….1
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
char *var, *value;
if(argc == 1 || argc > 3) {
fprintf(stderr,”usage: environ var *value+\n”);
               getenv, putenv ….2
fetch the value of the variable from the environment, using

var = argv[1];
value = getenv(var);
printf(“Variable %s has value %s\n”, var, value);
printf(“Variable %s has no value\n”, var);
                  getenv, putenv ….3
check whether the program was called with a second argument. If it was, you
   set the variable to the value of that argument by constructing a string of
   the form name=value and then calling putenv:

if(argc == 3) {
char *string;
value = argv[2];
string = malloc(strlen(var)+strlen(value)+2);
if(!string) {
fprintf(stderr,”out of memory\n”);
            getenv, putenv ….4
printf(“Calling putenv with: %s\n”,string);
if(putenv(string) != 0) {
fprintf(stderr,”putenv failed\n”);
               getenv, putenv ….5
Finally, you discover the new value of the variable by calling
   getenv once again:

value = getenv(var);
printf(“New value of %s is %s\n”, var, value);
printf(“New value of %s is null??\n”, var);
          Running the program
$ ./environ HOME
Variable HOME has value /home/neil
$ ./environ FRED
Variable FRED has no value
$ ./environ FRED hello
Variable FRED has no value
Calling putenv with: FRED=hello
New value of FRED is hello
$ ./environ FRED
Variable FRED has no value
    Use of Environment Variable
$ ./environ FRED
Variable FRED has no value
$ FRED=hello ./environ FRED
Variable FRED has value hello
               Extern char **environ
The variable environ points to an array of strings called the `environment‘

#include <stdlib.h>
#include <stdio.h>
extern char **environ;                $ ./showenv
int main()                  
{                                     LOGNAME=neil
char **env = environ;                 MAIL=/var/spool/mail/neil
while(*env) {                         HOSTTYPE=i386
env++;                                LS_OPTIONS=-N --color=tty -T 0
}                                     SHELL=/bin/bash
exit(0);                              OSTYPE=Linux
}                                     ……….
#include <time.h>
time_t time(time_t *tloc);
#include <time.h>
#include <stdio.h>                              $ ./envtime
#include <unistd.h>                             The time is 1179643852
#include <stdlib.h>                             The time is 1179643854
int main()                                      The time is 1179643856
{                                               The time is 1179643858
int i;                                          The time is 1179643860
time_t the_time;                                The time is 1179643862
for(i = 1; i <= 10; i++) {                      The time is 1179643864
the_time = time((time_t *)0);                   The time is 1179643866
printf(“The time is %ld\n”, the_time);          The time is 1179643868
sleep(2);                                       The time is 1179643870
#include <time.h>
double difftime(time_t time1, time_t time2);

#include <time.h>
struct tm *gmtime(const time_t timeval);
              tm members
tm Member     Description
int tm_sec    Seconds, 0-61
int tm_min    Minutes, 0-59
int tm_hour   Hours, 0-23
int tm_mday   Day in the month, 1-31
int tm_mon    Month in the year, 0-11 (January = 0)
int tm_year   Years since 1900
int tm_wday   Day in the week, 0-6 (Sunday = 0)
int tm_yday   Day in the year, 0-365
                      tm structure
struct tm {
int tm_sec;     /* seconds */
int tm_min;     /* minutes */
int tm_hour;    /* hours */
int tm_mday;    /* day of the month */
int tm_mon;     /* month */
int tm_year;    /* year */
int tm_wday;    /* day of the week */
int tm_yday;    /* day in the year */
int tm_isdst;   /* daylight saving time */
#include <time.h>
                                         $ ./gmtime; date
#include <stdio.h>
                                         Raw time is 1179644196
#include <stdlib.h>
                                         gmtime gives:
int main()
                                         date: 107/05/20
                                         time: 06:56:36
struct tm *tm_ptr;                       Sun May 20 07:56:37 BST 2007
time_t the_time;
(void) time(&the_time);
tm_ptr = gmtime(&the_time);
printf(“Raw time is %ld\n”, the_time);
printf(“gmtime gives:\n”);
printf(“date: %02d/%02d/%02d\n”,
tm_ptr->tm_year, tm_ptr->tm_mon+1, tm_ptr->tm_mday);
printf(“time: %02d:%02d:%02d\n”,
tm_ptr->tm_hour, tm_ptr->tm_min, tm_ptr->tm_sec);
#include <time.h>
struct tm *localtime(const time_t *timeval);
                 User Information…1
#include <sys/types.h>
#include <pwd.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main()
uid_t uid;
gid_t gid;
struct passwd *pw;
uid = getuid();
gid = getgid();
printf(“User is %s\n”, getlogin());
printf(“User IDs: uid=%d, gid=%d\n”, uid, gid);
            User Information…2
pw = getpwuid(uid);
printf(“UID passwd entry:\n name=%s, uid=%d, gid=%d,
   home=%s, shell=%s\n”,
pw->pw_name, pw->pw_uid, pw->pw_gid, pw->pw_dir, pw-
pw = getpwnam(“root”);
printf(“root passwd entry:\n”);
printf(“name=%s, uid=%d, gid=%d, home=%s, shell=%s\n”,
pw->pw_name, pw->pw_uid, pw->pw_gid, pw->pw_dir, pw-
$ ./user
User is neil
User IDs: uid=1000, gid=100
UID passwd entry:
name=neil, uid=1000, gid=100, home=/home/neil,
root passwd entry:
name=root, uid=0, gid=0, home=/root,
#include <pwd.h>
passwd Member       Description
char *pw_name       The user’s login name
uid_t pw_uid        The UID number
gid_t pw_gid        The GID number
char *pw_dir        The user’s home directory
char *pw_gecos      The user’s full name
char *pw_shell      The user’s default shell
        User & group identifier
#include <sys/types.h>
#include <unistd.h>

uid_t geteuid(void);
gid_t getgid(void);
gid_t getegid(void);
int setuid(uid_t uid);
int setgid(gid_t gid);
#include <sys/types.h>
#include <unistd.h>
pid_t getpid(void);
pid_t getppid(void);

The functions return the process and parent process
  identifiers of the calling process.
           Resources and Limits
• Programs running on a Linux system are subject
  to resource limitations.
• These might be physical limits imposed by
  – hardware (such as memory),
  – system policies (for example, allowed CPU time),
  – implementation limits (such as the size of an integer
    or the maximum number of characters allowed in a
• The UNIX specification defines some of these
  limits that can be determined by an application.

Limit Constant        Purpose
NAME_MAX The maximum number of characters in a
CHAR_BIT       The number of bits in a char value
CHAR_MAX The maximum char value
INT_MAX        The maximum int value
#include <sys/resource.h>               Integral for user
                                          and group ID

• int getpriority(int which, id_t who);
• int setpriority(int which, id_t who, int priority);
       •How much CPU time is
• int getrlimit(int resource, struct rlimit *r_limit);
       used by current program
       •Struct timeval ru_utime
• int setrlimit(int resource, const struct rlimit
       •Struct timeval ru_stime
• int getrusage(int who, struct rusage *r_usage);
• priority = getpriority(PRIO_PROCESS, getpid());

which Parameter       Description
PRIO_PROCESS          who is a process identifier.
PRIO_PGRP             who is a process group.
PRIO_USER             who is a user identifier.
            Resource Limits…1
• Include the header files for all the functions
  you’re going to be using in this program:
#include <sys/types.h>
#include <sys/resource.h>
#include <sys/time.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
                    Resource Limits…2
•    The void function writes a string to a temporary file 10,000 times and then
     performs some arithmetic to generate load on the CPU:
void work()
FILE *f;
int i;
double x = 4.5;
f = tmpfile();
for(i = 0; i < 10000; i++) {
fprintf(f,”Do some output\n”);
if(ferror(f)) {
fprintf(stderr,”Error writing to temporary file\n”);
for(i = 0; i < 1000000; i++)
x = log(x*x + 3.21);
               Resource Limits…3
• The main function calls work and then uses the getrusage function
    to discover how much CPU time it has used. It displays this
    information onscreen:
int main()
struct rusage r_usage;
struct rlimit r_limit;
int priority;
getrusage(RUSAGE_SELF, &r_usage);
printf(“CPU usage: User = %ld.%06ld, System = %ld.%06ld\n”,
r_usage.ru_utime.tv_sec, r_usage.ru_utime.tv_usec,
r_usage.ru_stime.tv_sec, r_usage.ru_stime.tv_usec);
             Resource Limits…4
• Next, it calls getpriority and getrlimit to find out
  its current priority and file size limits,
priority = getpriority(PRIO_PROCESS, getpid());
printf(“Current priority = %d\n”, priority);
getrlimit(RLIMIT_FSIZE, &r_limit);
printf(“Current FSIZE limit: soft = %ld, hard =
r_limit.rlim_cur, r_limit.rlim_max);
             Resource Limits…5
• Finally, set a file size limit using setrlimit and call
  work again, which fails because it attempts
to create too large a file:
r_limit.rlim_cur = 2048;
r_limit.rlim_max = 4096;
printf(“Setting a 2K file size limit\n”);
setrlimit(RLIMIT_FSIZE, &r_limit);
$ cc -o limits limits.c -lm
$ ./limits
CPU usage: User = 0.140008, System = 0.020001
Current priority = 0
Current FSIZE limit: soft = -1, hard = -1
Setting a 2K file size limit
File size limit exceeded

Description: file handling in linux Presentation by ali
Ali butt Ali butt Ali butt http://