Refreshing Netstat Output with Perl VIEW Rotwild, Photocase.Com

Total Page:16

File Type:pdf, Size:1020Kb

Refreshing Netstat Output with Perl VIEW Rotwild, Photocase.Com Perl: Dynamic netstat PROGRAMMING NETWORKRefreshing netstat output with Perl VIEW rotwild, photocase.com rotwild, The netstat utility reveals how your Linux box interacts with the local network. With a few Perl modules, you can develop a tool that displays the data dynamically, exactly the way top does. BY MICHAEL SCHILLI hen you want to know which Environment (POE), making it possible well as stdout events from other POE ports are currently being used, to execute many different tasks within a sessions. Wyou call netstat. This practical process or a thread. The netstat command should also play Linux utility can be run in several well with the POE kernel, which should modes, which the user controls through Don’t Freeze! start the process but not wait for the command-line options. For example, the As with all GUI applications that call result. Rather, it immediately should re- -s option produces network traffic statis- other programs, you will encounter a turn control to the kernel so that the tics (Figure 1), and -put displays the problem. While the external program latter can again refresh the output and ports of all applications that are cur- runs, the calling application no longer rently communicating over TCP (Figure reacts to user input and mouse clicks, 2). Both outputs are useful, but what is giving the user the impression that the really interesting is the chronological application is frozen. progression of events rather than a snap- The netstat command generally fin- shot at a given moment. ishes quite quickly, but with the -put op- tion, it resolves the hostname of the IP Top for the Network address associated with a socket with a The top utility serves as a model for this reverse DNS lookup. With a slow DNS kind of dynamic output, displaying and server or many sockets, this can lead to continually updating the CPU load, considerable delays; sometimes it takes memory usage, and other basic data of several seconds for netstat to complete. currently running processes. Thanks to Delays can be prevented with the -n op- CPAN, creating a dynamic terminal ap- tion, but the user must be content with plication like this from the static output just the IP address. But users want it all: from top is not really difficult. the luxury of name resolution and a fast- The Curses::UI module delivers the reacting GUI at the same time. necessary framework here, providing the dynamic output and making it possible Racer Components to react to keys pressed by the user. The The GUI application based on Curses::UI Figure 1: The netstat -s command delivers module’s event loop can be merged works together with the POE kernel, pro- statistical data about network traffic easily into the kernel of the Perl Object cessing key presses and mouse clicks as managed by Linux. APRIL 2008 ISSUE 89 73 073-078_perl.indd 73 13.02.2008 16:51:51 Uhr PROGRAMMING Perl: Dynamic netstat react to GUI events. If the output from netstat fi- nally arrives, the kernel again receives this as an event and calls a function that filters and stores the data into varaibles for subsequent processing. The POE::Wheel::Run module is a component of Figure 2: The output of the netstat -put command shows a list of all active TCP ports. the POE distribution from CPAN. The module takes care of an ex- automaton gets a time slice but must thing (hard disk, a network event, or ternal process and changes the state of guarantee that all of the registered ses- output from an external process) play an automaton in case something hap- sions eventually get a turn. In contrast along. An inconsiderate component can pens on the standard output of the pro- to a preemptive Linux kernel that some- paralyze the entire system. Each session cess. Other events occur if the process times pulls the rug out from under a pro- has a private data area – the heap – ends successfully or if an error occurs. cess, the POE framework relies on the which is implemented as hash and amicable behavior of all sessions. stores key-value pairs with session data. Wheels in the Kernel Each session must immediately return The wheel, in turn, finds its place in a control to the kernel, as soon as it can Autonomous Automatons POE::Session, a state automaton, which no longer run at full speed. With this co- The POE world encapsulates autono- latches itself into the POE kernel. The operative multitasking, it is important mous state automatons in so-called com- kernel ensures that now and then the that all tasks that are waiting for some- ponents. The application simply loads Listing 1: PoCoRunner.pm 01 package PoCoRunner; 31 61 $heap->{"wheel"} = $wheel; 02 use strict; 32 ############################# 62 $heap->{"stdout"} = ""; 03 use warnings; 33 sub _start { 63 } 04 use POE::Wheel::Run; 34 ############################# 64 05 use POE; 35 my ( $kernel, $session ) = 65 ############################# 06 36 @_[ KERNEL, SESSION ]; 66 sub stdout { 07 ############################# 37 $kernel->post( $session, 67 ############################# 08 our $PKG = __PACKAGE__; 38 "run" ); 68 my ( $input, $heap ) = 09 39 } 69 @_[ ARG0, HEAP ]; 10 ############################# 40 70 11 sub new { 41 ############################# 71 $heap->{stdout} .= 12 ############################# 42 sub run { 72 "$input\n"; 13 my ( $class, %options ) = 43 ############################# 73 } 14 @_; 44 my ( $kernel, $heap, 74 15 45 $session ) 75 ############################# 16 my $self = {%options}; 46 = @_[ KERNEL, HEAP, 76 sub finish { 17 47 SESSION ]; 77 ############################# 18 POE::Session->create( 48 78 my ( $kernel, $heap ) = 19 package_states => [ 49 my $wheel = 79 @_[ KERNEL, HEAP ]; 20 $PKG => [ 50 POE::Wheel::Run->new( 80 21 qw(_start stdout 51 Program => $heap->{self} 81 ${ $heap->{self}->{data} } 22 finish run) 52 ->{command}, 82 = $heap->{stdout}; 23 ] 53 ProgramArgs => [ 83 24 ], 54 $heap->{self}->{args} 84 $kernel->delay( "run", 25 heap => 55 ], 85 $heap->{self} 26 { self => $self }, 56 StdoutEvent => "stdout", 86 ->{interval} ); 27 ); 57 ErrorEvent => "finish", 87 } 28 58 CloseEvent => "finish", 88 29 bless $self, $class; 59 ); 89 1; 30 } 60 74 ISSUE 89 APRIL 2008 073-078_perl.indd 74 13.02.2008 16:52:05 Uhr Perl: Dynamic netstat PROGRAMMING these classes and creates new objects the constructor new->() has received a • _run: Fires off the process as needed, and the POE kernel includes reference to it from the calling program, • _stdout: Process sends a batch of data their state machines and runs them the main script nettop ends up with the to stdout autonomously behind the scenes. output data in either $stats_data or • _finish: Process terminates The PoCoRunner.pm listing (PoCo is $conns_data. POE maps these states to the functions the usual abbreviation for POE Compo- Subsequently, finish(), starting from of the same name within the module nent) shows a component that takes the line 76, calls the kernel method delay() PoCoRunner.pm, based on the parameter name of a program (netstat, for exam- and causes it to call the PocoRunner package_states in line 19. ple) with options and creates a “wheel,” method run() with a pre-defined delay, which then shoots off an external pro- which then resets the heap-variable data Parameters POE-Style cess with the given program (Listing 1). and again calls the wheel POE::Wheel:: POE passes session parameters in its Afterward, the wheel immediately re- Run with the specified external program own way; for example, if you have an turns control again to the kernel without netstat. event handler taking arguments like waiting for the result. Thus, if someone links this component With each line that appears on the into a POE program and calls the con- my($kernel, $heap) = standard output of the process, POE re- structor with an external command plus @_[KERNEL, HEAP]; ceives a stdout event and calls the PoCo- command-line parameters, an interval Runner.pm method stdout(). There, the duration, and a reference to a scalar, the the session passes the handler a set of session-specific heap variable data (a component not only starts the external arguments in the Perl-typical array @_. scalar) collects the process output as command again and again, but also The handler grabs only two of these text. If netstat has terminated, the au- ensures that the newest and complete through the macros KERNEL and HEAP. tomaton changes to the method finish(), output is stored in the scalar. These constant functions are imported regardless of whether the process has The PoCoRunner state automaton is by POE into the namespace and return terminated successfully or there was an defined by calling the POE::Session’s integer values, so the construct above error. It then copies the collected stdout create() method in line 18. represents a so-called array slice, which data into the scalar instance variable The states are: returns a subset of the parameters in the data of the PoCoRunner object. Because • _start: Start state array as a list. the mathematics of humour TWELVE Quirky Humans, Over Two Million Geeks around the world can’t be wrong! TWO Lovecraftian Horrors, COME JOIN THE INSANITY! ONE Acerbic A.I., ONE Fluffy Ball of Innocence and TEN Years of Archives EQUALS ONE Daily Cartoon that Covers the Geek Gestalt from zero to infinity! APRIL 2008 ISSUE 89 75 073-078_perl.indd 75 13.02.2008 16:52:05 Uhr PROGRAMMING Perl: Dynamic netstat The nettop listing (Listing 2) pulls in The function conns_parse in line 241 On the other hand, stats_parse in line two instances of PoCoRunner in lines 12 works through the netstat output (Figure 173 analyzes the output from netstat -s, and 18: one for netstat -s and an addi- 2), extracts the important columns (local as in Figure 1, and stores the output in a tional one for netstat -put.
Recommended publications
  • Windows Command Prompt Cheatsheet
    Windows Command Prompt Cheatsheet - Command line interface (as opposed to a GUI - graphical user interface) - Used to execute programs - Commands are small programs that do something useful - There are many commands already included with Windows, but we will use a few. - A filepath is where you are in the filesystem • C: is the C drive • C:\user\Documents is the Documents folder • C:\user\Documents\hello.c is a file in the Documents folder Command What it Does Usage dir Displays a list of a folder’s files dir (shows current folder) and subfolders dir myfolder cd Displays the name of the current cd filepath chdir directory or changes the current chdir filepath folder. cd .. (goes one directory up) md Creates a folder (directory) md folder-name mkdir mkdir folder-name rm Deletes a folder (directory) rm folder-name rmdir rmdir folder-name rm /s folder-name rmdir /s folder-name Note: if the folder isn’t empty, you must add the /s. copy Copies a file from one location to copy filepath-from filepath-to another move Moves file from one folder to move folder1\file.txt folder2\ another ren Changes the name of a file ren file1 file2 rename del Deletes one or more files del filename exit Exits batch script or current exit command control echo Used to display a message or to echo message turn off/on messages in batch scripts type Displays contents of a text file type myfile.txt fc Compares two files and displays fc file1 file2 the difference between them cls Clears the screen cls help Provides more details about help (lists all commands) DOS/Command Prompt help command commands Source: https://technet.microsoft.com/en-us/library/cc754340.aspx.
    [Show full text]
  • Lab - Observing DNS Resolution (Instructor Version) Instructor Note: Red Font Color Or Gray Highlights Indicate Text That Appears in the Instructor Copy Only
    Lab - Observing DNS Resolution (Instructor Version) Instructor Note: Red font color or Gray highlights indicate text that appears in the instructor copy only. Objectives Part 1: Observe the DNS Conversion of a URL to an IP Address Part 2: Observe DNS Lookup Using the Nslookup Command on a Web Site Part 3: Observe DNS Lookup Using the Nslookup Command on Mail Servers Background / Scenario The Domain Name System (DNS) is invoked when you type a Uniform Resource Locator (URL), such as http://www.cisco.com, into a web browser. The first part of the URL describes which protocol is used. Common protocols are Hypertext Transfer Protocol (HTTP), Hypertext Transfer Protocol over Secure Socket Layer (HTTPS), and File Transfer Protocol (FTP). DNS uses the second part of the URL, which in this example is www.cisco.com. DNS translates the domain name (www.cisco.com) to an IP address to allow the source host to reach the destination host. In this lab, you will observe DNS in action and use the nslookup (name server lookup) command to obtain additional DNS information. Work with a partner to complete this lab. Required Resources 1 PC (Windows 7, Vista, or XP with Internet and command prompt access) Part 1: Observe the DNS Conversion of a URL to an IP Address a. Click the Windows Start button, type cmd into the search field, and press Enter. The command prompt window appears. b. At the command prompt, ping the URL for the Internet Corporation for Assigned Names and Numbers (ICANN) at www.icann.org. ICANN coordinates the DNS, IP addresses, top-level domain name system management, and root server system management functions.
    [Show full text]
  • Shells and Shell Scripting
    Shells and Shell scripting What is a Shell? • A shell is a command line interpreter that is the interface between the user and the OS. • A “program launcher” of sorts. • The shell: o analyzes each command o determines what actions are to be performed o performs the actions • Example: wc –l file1 > file2 Which shell? • sh – Bourne shell o Most common, other shells are a superset o Good for programming • csh or tcsh – default for command line on CDF o C-like syntax o Best for interactive use. Not good for programming. • bash – default on Linux (Bourne again shell) o Based on sh, with some csh features. • korn – written by David Korn o Based on sh – Some claim best for programming. o Commercial product. Common shell facilities Shell startup When a shell is invoked, it does the following: 1. Read a special startup file (usually in home directory) 2. display prompt and wait for command 3. Ctrl-D on its own line terminates shell, otherwise, goto step 2. Shell startup files used to set shell options, set up environment variables, alias sh – executes .profile if it’s there. ksh – executes .profile if in interactive mode. Executes $ENV (usually $HOME/.kshrc) csh – executes .cshrc if it exists. If a login shell, executes .login bash – executes .bashrc, if a login shell, executes .bash_profile instead Executables vs. built-in commands Most commands you run are other compiled programs. Found in /bin Example: ls – shell locates ls binary in /bin directory and launches it Some are not compiled programs, but built into the shell: cd, echo Input-output redirection prog < infile > outfile ls > outfile 2>&1 # sh stdout and stderr Pipelining commands send the output from one command to the input of the next: ls -l | wc ps –aux | grep reid | sort Before a program is executed, the shell recognizes the special characters such as <, >, |, and rewires the standard input, output, or error file descriptors of the program about to be executed to point to the right files (or the standard input of another program).
    [Show full text]
  • NETSTAT Command
    NETSTAT Command | NETSTAT Command | Use the NETSTAT command to display network status of the local host. | | ┌┐────────────── | 55──NETSTAT─────6─┤ Option ├─┴──┬────────────────────────────────── ┬ ─ ─ ─ ────────────────────────────────────────5% | │┌┐───────────────────── │ | └─(──SELect───6─┤ Select_String ├─┴ ─ ┘ | Option: | ┌┐─COnn────── (1, 2) ──────────────── | ├──┼─────────────────────────── ┼ ─ ──────────────────────────────────────────────────────────────────────────────┤ | ├─ALL───(2)──────────────────── ┤ | ├─ALLConn─────(1, 2) ────────────── ┤ | ├─ARp ipaddress───────────── ┤ | ├─CLients─────────────────── ┤ | ├─DEvlinks────────────────── ┤ | ├─Gate───(3)─────────────────── ┤ | ├─┬─Help─ ┬─ ───────────────── ┤ | │└┘─?──── │ | ├─HOme────────────────────── ┤ | │┌┐─2ð────── │ | ├─Interval─────(1, 2) ─┼───────── ┼─ ┤ | │└┘─seconds─ │ | ├─LEVel───────────────────── ┤ | ├─POOLsize────────────────── ┤ | ├─SOCKets─────────────────── ┤ | ├─TCp serverid───(1) ─────────── ┤ | ├─TELnet───(4)───────────────── ┤ | ├─Up──────────────────────── ┤ | └┘─┤ Command ├───(5)──────────── | Command: | ├──┬─CP cp_command───(6) ─ ┬ ────────────────────────────────────────────────────────────────────────────────────────┤ | ├─DELarp ipaddress─ ┤ | ├─DRop conn_num──── ┤ | └─RESETPool──────── ┘ | Select_String: | ├─ ─┬─ipaddress────(3) ┬ ─ ───────────────────────────────────────────────────────────────────────────────────────────┤ | ├─ldev_num─────(4) ┤ | └─userid────(2) ─── ┘ | Notes: | 1 Only ALLCON, CONN and TCP are valid with INTERVAL. | 2 The userid
    [Show full text]
  • Introduction to Unix Shell
    Introduction to Unix Shell François Serra, David Castillo, Marc A. Marti- Renom Genome Biology Group (CNAG) Structural Genomics Group (CRG) Run Store Programs Data Communicate Interact with each other with us The Unix Shell Introduction Interact with us Rewiring Telepathy Typewriter Speech WIMP The Unix Shell Introduction user logs in The Unix Shell Introduction user logs in user types command The Unix Shell Introduction user logs in user types command computer executes command and prints output The Unix Shell Introduction user logs in user types command computer executes command and prints output user types another command The Unix Shell Introduction user logs in user types command computer executes command and prints output user types another command computer executes command and prints output The Unix Shell Introduction user logs in user types command computer executes command and prints output user types another command computer executes command and prints output ⋮ user logs off The Unix Shell Introduction user logs in user types command computer executes command and prints output user types another command computer executes command and prints output ⋮ user logs off The Unix Shell Introduction user logs in user types command computer executes command and prints output user types another command computer executes command and prints output ⋮ user logs off shell The Unix Shell Introduction user logs in user types command computer executes command and prints output user types another command computer executes command and prints output
    [Show full text]
  • Command-Line IP Utilities This Document Lists Windows Command-Line Utilities That You Can Use to Obtain TCP/IP Configuration Information and Test IP Connectivity
    Guide to TCP/IP: IPv6 and IPv4, 5th Edition, ISBN 978-13059-4695-8 Command-Line IP Utilities This document lists Windows command-line utilities that you can use to obtain TCP/IP configuration information and test IP connectivity. Command parameters and uses are listed for the following utilities in Tables 1 through 9: ■ Arp ■ Ipconfig ■ Netsh ■ Netstat ■ Pathping ■ Ping ■ Route ■ Tracert ARP The Arp utility reads and manipulates local ARP tables (data link address-to-IP address tables). Syntax arp -s inet_addr eth_addr [if_addr] arp -d inet_addr [if_addr] arp -a [inet_address] [-N if_addr] [-v] Table 1 ARP command parameters and uses Parameter Description -a or -g Displays current entries in the ARP cache. If inet_addr is specified, the IP and data link address of the specified computer appear. If more than one network interface uses ARP, entries for each ARP table appear. inet_addr Specifies an Internet address. -N if_addr Displays the ARP entries for the network interface specified by if_addr. -v Displays the ARP entries in verbose mode. -d Deletes the host specified by inet_addr. -s Adds the host and associates the Internet address inet_addr with the data link address eth_addr. The physical address is given as six hexadecimal bytes separated by hyphens. The entry is permanent. eth_addr Specifies physical address. if_addr If present, this specifies the Internet address of the interface whose address translation table should be modified. If not present, the first applicable interface will be used. Pyles, Carrell, and Tittel 1 Guide to TCP/IP: IPv6 and IPv4, 5th Edition, ISBN 978-13059-4695-8 IPCONFIG The Ipconfig utility displays and modifies IP address configuration information.
    [Show full text]
  • Freebsd Command Reference
    FreeBSD command reference Command structure Each line you type at the Unix shell consists of a command optionally followed by some arguments , e.g. ls -l /etc/passwd | | | cmd arg1 arg2 Almost all commands are just programs in the filesystem, e.g. "ls" is actually /bin/ls. A few are built- in to the shell. All commands and filenames are case-sensitive. Unless told otherwise, the command will run in the "foreground" - that is, you won't be returned to the shell prompt until it has finished. You can press Ctrl + C to terminate it. Colour code command [args...] Command which shows information command [args...] Command which modifies your current session or system settings, but changes will be lost when you exit your shell or reboot command [args...] Command which permanently affects the state of your system Getting out of trouble ^C (Ctrl-C) Terminate the current command ^U (Ctrl-U) Clear to start of line reset Reset terminal settings. If in xterm, try Ctrl+Middle mouse button stty sane and select "Do Full Reset" exit Exit from the shell logout ESC :q! ENTER Quit from vi without saving Finding documentation man cmd Show manual page for command "cmd". If a page with the same man 5 cmd name exists in multiple sections, you can give the section number, man -a cmd or -a to show pages from all sections. man -k str Search for string"str" in the manual index man hier Description of directory structure cd /usr/share/doc; ls Browse system documentation and examples. Note especially cd /usr/share/examples; ls /usr/share/doc/en/books/handbook/index.html cd /usr/local/share/doc; ls Browse package documentation and examples cd /usr/local/share/examples On the web: www.freebsd.org Includes handbook, searchable mailing list archives System status Alt-F1 ..
    [Show full text]
  • Networking TCP/IP Troubleshooting 7.1
    IBM IBM i Networking TCP/IP troubleshooting 7.1 IBM IBM i Networking TCP/IP troubleshooting 7.1 Note Before using this information and the product it supports, read the information in “Notices,” on page 79. This edition applies to IBM i 7.1 (product number 5770-SS1) and to all subsequent releases and modifications until otherwise indicated in new editions. This version does not run on all reduced instruction set computer (RISC) models nor does it run on CISC models. © Copyright IBM Corporation 1997, 2008. US Government Users Restricted Rights – Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp. Contents TCP/IP troubleshooting ........ 1 Server table ............ 34 PDF file for TCP/IP troubleshooting ...... 1 Checking jobs, job logs, and message logs .. 63 Troubleshooting tools and techniques ...... 1 Verifying that necessary jobs exist .... 64 Tools to verify your network structure ..... 1 Checking the job logs for error messages Netstat .............. 1 and other indication of problems .... 65 Using Netstat from a character-based Changing the message logging level on job interface ............. 2 descriptions and active jobs ...... 65 Using Netstat from System i Navigator .. 4 Other job considerations ....... 66 Ping ............... 7 Checking for active filter rules ...... 67 Using Ping from a character-based interface 7 Verifying system startup considerations for Using Ping from System i Navigator ... 10 networking ............ 68 Common error messages ....... 13 Starting subsystems ........ 68 PING parameters ......... 14 Starting TCP/IP .......... 68 Trace route ............ 14 Starting interfaces ......... 69 Using trace route from a character-based Starting servers .......... 69 interface ............ 15 Timing considerations ........ 70 Using trace route from System i Navigator 15 Varying on lines, controllers, and devices .
    [Show full text]
  • Unix Basic Command
    SOI Asia Workshop 2008 Pre-workshop Unix Basic Assignment This document aims to provide basic Unix commands that operator needs to know to be able to follow lecture content of SOI Asia operator workshop. Participant should review the usage and do a practice on SOI Asia server with guidance and further explanation from senior SOI Asia operator at your site. To do practice, you need a user account on SOI Asia server machine and root password. Remember to always use your user account to do practice unless the practicing command really require root permission. 1. User account command passwd : Change your password. This will let you enter a new password. Please use a password that is not a real word or name and has numbers or punctuation in it. Practice. Login your user and change password to new one. Do not practice this command with root user. # passwd su : Become another user “su username” attempt to login as another user, system authenticate by prompting password. Without specifying username, it is attempt to login as root. exit : Logout When you are login as a user, you logout by this command. whoami : Check the current being user It returns username that you are using now. Practice. Login your user, and check current being user. “su” to be root, and check that your user is changing to root. Logout user root, and check your user again. # whoami # su # whoami # exit # whoami 2. Manual and Process command man : Show any UNIX command usages “man command” shows purpose of command, its format, how to specify options and usage examples.
    [Show full text]
  • 1 Introduction to Shell Programming
    1 Introduction to Shell Programming This lecture is prepared for beginners who wish to learn the basics of shell scripting/programming plus introduction to power tools such as awk, sed, etc. 1.1 What is Linux Shell? • In Operating System, there is special program called Shell. Shell ac- cepts your instruction or commands in English (mostly) and if its a valid command, it is passed to kernel. • Shell is a user program or it's a environment provided for user interac- tion. • Shell is an command language interpreter that executes commands read from the standard input device (keyboard) or from a file. • Shell is not part of system kernel, but uses the system kernel to execute programs, create files etc. • To find all available shells in your system type following command: $ cat /etc/shells • Note that each shell does the same job, but each understand a different command syntax and provides different built-in functions. • In MS-DOS, Shell name is COMMAND.COM which is also used for same purpose, but it's not as powerful as our Linux Shells are! • To find your current shell type following command $ echo $SHELL • To use shell (You start to use your shell as soon as you log into your system) you have to simply type commands. 1 1.2 What is Shell Script ? • Normally shells are interactive. It means shell accept command from you (via keyboard) and execute them. • But if you use command one by one (sequence of 'n' number of com- mands) , the you can store this sequence of command to text file and tell the shell to execute this text file instead of entering the commands.
    [Show full text]
  • Behind the 'System(…)' Command Execv Execl
    Computer Systems II Execung Processes 1 Behind the ‘system(…)’ Command execv execl 2 1 Recall: system() Example call: system(“mkdir systest”); • mkdir is the name of the executable program • systest is the argument passed to the executable mkdir.c int main(int argc, char * argv[]) { ... // create directory called argv[1] ... } 3 Unix’s execv The system call execv executes a file, transforming the calling process into a new process. AFer a successful execv, there is no return to the calling process. execv(const char * path, const char * argv[]) • path is the full path for the file to be executed • argv is the argument array, starGng with the program name • each argument is a null-terminated string • the first argument is the name of the program • the last entry in argv is NULL 4 2 system() vs. execv system(“mkdir systest”); mkdir.c int main(int argc, char * argv[]) { ... // create directory called argv[1] ... } char * argv[] = {“/bin/mkdir”, “systest”, NULL}; execv(argv[0], argv); 5 How execv Works (1) pid = 25 pid = 26 Data Resources Data Text Text Stack Stack PCB File PCB char * argv[ ] = {“/bin/ls”, 0}; cpid = 26 cpid = 0 char * argv[ ] = {“/bin/ls”, 0}; <…> <…> int cpid = fork( ); int cpid = fork( ); if (cpid = = 0) { if (cpid = = 0) { execv(argv[0], argv); execv(argv[0], argv); exit(0); exit(0); } } <parent code> <parent code> wait(&cpid); wait(&cpid); /bin/ls UNIX kernel 6 3 How execv Works (2) pid = 25 pid = 26 Data Resources Text Stack PCB File char * argv[ ] = {“/bin/ls”, 0}; cpid = 26 <…> Exec destroys the int cpid = fork( ); if (cpid = = 0) { process image of the execv(argv[0], argv); calling process.
    [Show full text]
  • Introduction to the Command Line Getting Started with Windows Powershell
    Introduction To The Command Line Getting started with Windows Powershell The Command Line is a text-based interface that allows you to communicate with your computer to accomplish a wide range of tasks. You will use the skills you develop in this lesson when working with Twarc, a command line tool for collecting and analyzing Twitter data. It is ​ ​ important to have a handle on basic commands so that you can work with the 1 October Twitter Data Collection later on in this tutorial series. Get started by downloading the materials below! Difficulty level: Beginner ​ Optimized for: Windows users. Mac users can view the tutorial here. ​ ​ ​ Prerequisite(s): None ​ Materials: Download ‘walt_whitman.zip’ to your desktop ​ ​ Tutorial Key ● Command Line commands will be displayed in this format ● means you have come to the end of a set of instructions Lesson objectives - Use the command line to navigate your computer - Create and move content around - Make changes to existing files Key Terms ● PowerShell - Command Line Shell from Microsoft ○ A text interface for your computer. PowerShell receives commands and then passes those commands on to the computer's operating system to run. ● Command ○ A specific order from a user to the computer’s operating system to perform a service ● Graphical-User Interface (GUI) ○ A visual form of user interface that allows users to interact with a computer through icons and other visual indicators ● Filepath ○ A unique address that specifies a location in a file system ● Directory ○ A location for storing files on your computer. A directory is the same thing as a folder; a folder is represented visually in a GUI.
    [Show full text]