C running same program twice in LINUX [closed] - c

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am wondering if it is possible to run same program twice, and every time it does something different. For instance I have two programs one that writes with fifo pipes and one that reads from it. So there are programA.c and programB.c (simple program, just sending some integers).
But I would like to run it like that:
./program & sleep 1; ./program
So one program would have two operation modes.
Thanks.

Yes, it is possible. You can run a program however many times you want. However, you may need to ensure that two instances of the same program do not contend for the same resources; for instance, if they both write to the same file, unexpected results may occur.
If you want the same program to do two different things (one writing to the fifo and one reading from it) you will have to ensure that the program can determine which action to take. One way of doing this would be to parse command-line parameters (e.g. invoke one as myprog --read and the other as myprog --write. Another would be for the program first to check for the existence of the fifo; if it doesn't exist, it could create the fifo and write to it, and if it does exist it could read from it.

Write your program to accept command line arguments like sed or awk.
Here is a simple example in C:
#include <stdio.h>
int main( int argc, char *argv[] ) {
if( argc == 1 ) printf("You passed in zero arguments and your program is named %s\n", argv[0]);
if( argc > 1 ){
int x;
for(x = 1; x < argc; x++)
printf("Argument %d is named %s\n",x, argv[x]); //print multiple arguments
}
return 0;
}
If you compile and run this program with no arguments it will tell you that you didn't pass in any arguments; otherwise, you can pass in as many command line arguments as you like and it will print them back out for you.
The point is that this one program does different things depending on the arguments passed into it.

Related

Undestanding for loop in pipe creation in C [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a comprension question about this code that I am currently studying: this function is used in a C Shell implementation to execute piped commands. I can't understand how the person who wrote it got to know how many pipes to close (why is the limit 2*com- 2)?
for(i = 0; i < 2*com - 2; i++) close(pip[i]);
for(i = 0; i < com; ++i) {
waitpid(pid, &status, WUNTRACED);
In this program, num_pipe is not actually the number of pipes
but the number of commands (very bad name indeed!).
Between two commands you need one pipe, between three commands
you need two pipes ... between N commands you need N-1 pipes.
Each pipe relies on two file descriptors (one for reading, one
for writing) thus 2*(num_pipe-1) file descriptors are needed
for num_pipe commands.
note: the malloc() does not allocate an array of integer pointers
(as stated in the question) but an array of integers.
Following this logic, I would have written
for(i = 0; i < 2*(num_pipe-1); i += 2)
but 2*(num_pipe-1) equals to 2*num_pipe-2 and since the step
is 2, the loop condition is the same with the limit
2*num_pipe-3.
It's just terribly confusing in my opinion.

Array access args[0][1]-'0' [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have searched for any reference to this for quite a bit now but I haven't had any success, so I thought I would ask here. Basically, I am trying to understand a C written program for creating a shell in linux and I am having problems with this piece of code
...
else if (args[0][0]-'!'==0){
int x = args[0][1]-'0';
int z = args[0][2]-'0';
...
}
The args is storing the command's entered by the user. For instance, later the address space of the child (parent process reads the commands, child executes them) is replaced using a call to execvp(args[0], args). The definition of args is as follows: char *args[MAX_LINE/2 +1];
What I have been having trouble understanding is the ways in which the array is accessed; specifically what is meant by these expressions in this context:
args[0][0]-'!'==0
args[0][1]-'0';
args[0][2]-'0';
Judging by the name of the variable, args stands for a list/array of arguments.
arg[0] is the first element of that array.
args[0][0] is the first character of the first element of that array.
The expression args[0][0]-'!'==0 checks whether that character is equal to '!'. That could have been written better as args[0][0] == '!'.
It's as if instead of using if ( i == 10 ), you decide to use if (i-10 == 0).
The next two lines
int x = args[0][1]-'0';
int z = args[0][2]-'0';
expect that the second and third characters of the first argument are digits and extract the decimal values they correspond to. If the first argument is "!26", then x will have the value 2 and z will have the value 6.
That logic depends on the guarantee that the encoding used for the characters '0' - '9' are required to be contiguous.
Probably args is a reference to
int main(int argc, char **argv);
Then args[0] is the name of the program and in the following args you would find the Arguments of the Programm, see e.g. Arguments to main in C
Thus args[0[0] is the first character of the name of the program.

Runtime error when running my code [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
When I compile my C codes sometimes I get this error message.
Mycode.exe has stopped working..
A problem caused the program to stop working correctly.
Windows will close the program and notify you if a solution available.
My C code :
#include<stdio.h>
main(){
char a;
a="S";
printf("%s",a);
}
So what is the reason for this problem?
Syntax error, Runtime error or another reason?
When you invoke printf with %s it means that printf will start printing at the given address and end when a null terminator is reached, because you are giving printf a char and not a pointer to a char, it tries to use the value written in a to start printing from.
a is a char taking up a space of one Byte while an address is 8 Bytes in a 64 bit system, so basically printf takes the value in 'a' and the the next 7 Bytes(which are random 'garbage') and tries to use it as an address to stop printing.
that is why it sometimes works as you said, sometimes those random addresses are fine to start printing from, but sometimes they are addresses that you are not authorized to access like areas of memory used by the OS or kernel.
to solve the problem you need to make a a char * and not a char, and assign it with a string.
Change your code to
#include<stdio.h>
int main()
{
char a;
a='S';
printf("%c",a);
return 0;
}
and it will work fine.

argc and argv[] in C language [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I'm learning C and in one of the examples we write a program like this:
#include <stdio.h>
int main(int argc, char *argv[])
{
// go through each string in argv
int i = 0;
while(i < argc)
{
printf("arg %d: %s\n", i, argv[i]);
i++;
}
// let's make our own array of stringd
char *states[] = {"California", "Oregon", "Washington", "Texas"};
int num_states = 4;
i = 0; // watch for this
while(i < num_states)
{
printf("state %d: %s\n", i, states[i]);
i++;
}
return 0;
}
and if I run it in terminal like this:
./ex11 test arguments
I get an output of:
arg 0: ./ex11
arg 1: test
arg 2: arguments
state 0: California
state 1: Oregon
state 2: Washington
state 3: Texas
However I don't understand why the "Test argument" part gets printed, i know it has something to do with argc and argv but I don't know how.
Can someone explain this to me (preferably in a simple manner)?
When a command, any command, is run by the shell (actually, any shell) on Unix, then the command line is converted into an array of strings:
cmd_argv[0] = "./ex11";
cmd_argv[1] = "test";
cmd_argv[2] = "arguments";
cmd_argv[3] = NULL;
cmd_argc = 3;
and then invokes:
execvp(cmd_argv[0], cmd_argv);
Note that all I/O redirections are removed, etc. Internally, the system ends up counting the number of non-null pointers at the start of the cmd_argv array and passes them as argv in the new program, and the count as argc. The new program is guaranteed that argc >= 0 and argv[argc] == NULL.
This list is almost the same form as the list of states; the primary difference is that cmd_argv[cmd_argc] is a null pointer, which is certainly not guaranteed with the states data.
That's what your first loop does, it iterates through the strings in argv (which contains the name of the program and the arguments you typed after it), and prints them out. Argc is the number of arguments you passed, or equivalently the length of argv.
argv is the command line arguments, including the executable's name (aguments' values). argc is the amount of elements in argv (argument count).
In your first loop, you are printing the contents of argv, therefore you get the arguments that were passed to your program.

main arguments and functions in c [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
#include <stdio.h>
int multiply(int n){
int doenstwork = n * 2;
return doesntwork;
}
int main(int argc, char *argv[]){
int n;
n = atoi(argv[1]);
return multiply(n);
}
I compile but when i run it with an argument I see nothing. Compiled it with gcc -std=c99 filename.c -g.
With the updated code in your question, you have several problems:
You have a typo: you declare a variable doenstwork, but then you try to refer to doesntwork.
Since you say you're able to compile and run your program, what you posted is obviously not the same as what you're actually running. Always copy-and-paste your exact code. If you re-type it, you'll make mistakes like this, and those of us trying to help you can't tell the difference between mistakes you made entering the code in your question and mistakes that are actually in the code you're compiling and running.
The value returned from main is the status of your program, not its output. On Unix-like systems, all but the low-order 8 bits of this value are ignored, so this is not a good way for your program to return detailed information.
Once I corrected the typo, I was able to use your program:
$ gcc c.c -o c
$ ./c 7 ; echo $?
14
but it works only for a small range of values:
$ ./c 1000 ; echo $?
208
The status of a program is used to indicate whether it succeeded or failed, and possibly to return a small amount of information about why it failed. Returning a value of 0 denotes successful execution; returning EXIT_FAILURE (defined in <stdlib.h>) denotes failure. On Unix-like systems, usually EXIT_FAILURE == 1; sometimes a value like 2 is used to denote a different kind of failure. For example, grep returns a status of 0 if a match was found, 1 if no match was found, and 2 if something else went wrong (such as a malformed regular expression or a missing file).
To get information out of a program, the simplest way is to print that information in text form to standard output. You can replace
return multiply(n);
by
printf("%d\n", multiply(n));
You can add a return 0; after that; as of C99 it's not required, but it's not a bad idea to be explicit.
You don't define the variable "doesntwork". This shouldn't compile.
You don't end your function "multiply" with a closing bracket. This shouldn't compile.
You don't include a function prototype for the function "multiply". This shouldn't compile.
If your IDE is so lazy that it will compile this then how do you know that it "didn't work"? Maybe it returned some int to the OS.
Actually Billy Bob is correct. Different IDEs and compilers require different levels of strictness. Full ANSI/ISO compliance, requiring prototypes, etc. can save you a lot of trouble. Your compiler SHOULD require a prototype.
The line:
n = atoi(argv[1]);
is suspicious as well because in C arrays are indexed from zero so the first item in your array should be argv[0].

Resources