question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
I am trying to parse a string from stdin such as this one{ 7 , 3,5 ,11, 8, 16, 4, 9, 2
,8, 4, 2}( there is a \n between 2 and 8 ).
I have made a function to extract the numbers and trim commas spaces and newlines (accepts char* as an input) but the problem is when I try to get input using scanf I can't get spaces so I used fgets instead but fgets will exit as soon as it sees \n.
Is there a way I can get a string from this ?
|
```
int nums[1000], count = 0;
char chr;
while(scanf("%c%d", &chr, &nums[count]) > 0) //there was at least one match
{
if(chr == '}')
break; //we have reached the end
if(chr != ',' && chr != '{')
continue; //skip spaces (} is an exception)
count++;
}
```
|
So I have a string "127.0.0.1:1024"
I want to split the127.0.0.1from1024. This is what I've tried:
```
char server[2048], port[2048];
int scanErr = sscanf(argv[1], "%[^:]2047s:%2047s", server, port);
```
It gets the127.0.0.1right, but port is still empty. What could be the problem?
|
You don't need extra info after%[]:
```
sscanf(argv[1], "%15[^:]:%5s", server, port);
```
Plus, I don't really think you needthatmuch space for them:
```
char server[16], port[6];
```
|
So I'm reading from a file descriptor which contains anintvariable in its raw byte format.
So I'm doing:
```
char buffer[sizeof(int)];
ssize_t sizeOfFile = read(sock_fd, buffer, sizeof(int));
int extractedInt = ???;
```
How can I convert that buffer to an integer? I was thinking of memcpy but was wondering if there are better ways.
|
You could read directly an integer
```
int extractedInt;
ssize_t sizeOfFile = read(sock_fd, &extractedInt, sizeof(int));
```
readwill read the size of an int bytes, and store them intoextractedInt.
If yourintis actually a string in a file you want to convert to anint, the procedure is a bit different.
```
#define SIZE 20
char buffer[SIZE]; // ensure there is enough space for a string containing an integer
ssize_t sizeOfFile = read(sock_fd, buffer, SIZE);
int extractedInt = atoi(buffer); // convert string to integer
```
|
I'm trying to send raw bytes of a variable to a certain file descriptor (in this case a socket).
So let's say I have:
```
size_t number = 3;
write(some_fd, number, sizeof(size_t));
```
So would that write thesizeof(size_t)number of bytes of the variablenumberto the file descriptorsome_fd?
I have no way of testing this out currently, so just wanted to confrm.
|
So would that write thesizeof(size_t)number of bytes of the variable number to the file descriptorsome_fd?
No, it won't.
Remember thatwriteis declared as:
```
ssize_t write(int fildes, const void *buf, size_t nbyte);
```
You'd need to use:
```
write(some_fd, &number, sizeof(size_t));
// ^^^
```
Use of&is necessary to be able write the value ofnumberfrom the address used bynumber.
|
In Code::Blocks when i run and debug my code it says in the "Build messages section" (error: Cannot find id) I reinstalled both the coding platform (code::blocks) and the compiler individually and nothing has changed.
|
Try simple program first to see if installation is correct:
```
#include <stdio.h>
int main()
{
printf("Hello World");
return 0;
}
```
|
I can read unsigned ints from a binary file but one of the values is printing out negative.
Expected values:
45788331,
281302247,
461354227,
13127,
299215653,
2356985123,
Values printed out:
45788331,
281302247,
461354227,
13127,
299215653,
-1932982173,
The 6th value is printing out as negative but I am reading a list of unsigned ints?
My code below
```
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE * fp;
ssize_t read;
int r = 0;
fp = fopen("numbers.bin", "rb");
if (fp == NULL)
exit(-1);
while(fread(&r, sizeof(unsigned int), 1, fp) == 1)
{
printf("%d\n", r);
}
fclose(fp);
if (line) free(line);
exit(0);
}
```
|
printf("%d\n", r);prints out asigneddecimal integer.
You want:printf("%u\n", r);
Additionally,ris declared asintnotunsigned int.
|
Can I safely usememmem()if I want it to also run on Mac?
I know it requires:
```
#define _GNU_SOURCE
#include <string.h>
```
|
Yes,memmemis available on MacOS. Seethe man pagefor details.
You don't however need to#define _GNU_SOURCE. That is specific to Linux.
|
I was working with argv to store characters from the command line. And I just noted that if I input#I got a null instead of character#. Why is this happening?
```
#include <stdio.h>
int main(int argc,char *argv[])
{
printf("%c",argv[1][0]);
}
```
The code above works fine with any character, except#which returns Segmentation fault (core dumped) .
|
The#character denotes the start of a comment to the shell, so it never gets to your program. As a result,argvonly has one element, i.e.argv[0], so accessingargv[1]is reading off the end of the array. This invokesundefined behavior, which in this case manifests in a crash.
In order for the shell to pass this special character to your program, you need to quote it:
```
./myprogram "#"
```
|
In functionmy_func1()in c the 1st thing I do is call another functionmy_func2(), which always sets the pointer.GCCwarns me that the pointer might not be set. How can I get rid of the warning?
Here's some simplified code to merely demonstrate it.
```
int bla;
void my_func2(int *ptr) {
ptr = &bla;
}
void my_func1() {
int *ptr;
//ptr=0;
my_func2(ptr);
}
```
If the lineptr=0is uncommented, then the warning goes away. I don't want to set the variable because it does nothing since themy_func2()sets it.
Thegccwarning message is
warning: 'ptr' is used uninitialized in this function
[-Wuninitialized]
Any help would be greatly appreciated.
|
I think what you're trying to do is this:
```
int bla;
void my_func2(int **pp) {
*pp = &bla;
}
void my_func1() {
int *ptr;
my_func2(&ptr);
...
}
```
|
try to input 20 numbers with array and to output
the numbers in the double location only but somehow it's print
also the 0 location... please help.
```
#include<stdio.h>
#define n 20
int main()
{
int num[n]={0},i=0,order=1,double_locaion=0;
for(i=0;i<n;i++)
{
printf("please enter %d number\n",order);
scanf("%d",&num[i]);
order++;
}
for(i=0;i<n;i++)
{
if (i%2==0 && i!=1 && i!=0)
{
printf("%d\n",num[i]);
}
}
}
```
|
Try this, start with 2 and increase by 2 every time, the you don't have to deal with 0th element and odd element.
```
for (i = 2; i < n; i += 2)
{
printf("%d\n",num[i]);
}
```
|
guys!
Why i can't take address of "t" - variable ?
```
flygs->type == 'X' ? t = a_ib_u(u->us, 16) : (a_lowcasealph(&(t = a_ib_u(u->us, 16))));
\\a_ib_u returns *char, a_lowcasealph take **char argument
```
error: cannot take the address of an rvalue of type 'char *'
|
The answer by @dbush have already explained the cause of the error.
I like to add that you can rewrite the code and get something much easier to understand and maintain. Like:
```
t = a_ib_u(u->us, 16);
if (flygs->type != 'X') a_lowcasealph(&t);
```
|
I have an array which I wish to assign zeros to all positions in a given range (positions 10 to 24, in this case). I'm doing this:
```
ulong st[25];
...
for(int i = 10; i < 25; ++i) st[i] = 0x00UL;
```
Is this the fastest way to do that? It seems that there should be a faster way without a loop, given that it's a contiguous position in memory, but I don't know what that would be (perhaps XORing that memory space with itself? If so, how would I do that?)
Any ideas?
|
I'd be tempted to write it with the simple loop as you have done, and leave the optimisation trickery to the compiler.
If you are in any doubt that the compiler has done a good job then check the generated assembly.
As a rule of thumb, programmers are more expensive than computers. So keep maintenance cheap; i.e. write clear code whenever possible.
|
Can i cast type to va_arg return as on example?
As i know va_arg can't read-return char/short int types
```
if (flags->size == 0)
u->s = (char)va_arg(pt, int);
if (flags->size == 1)
u->s = (short int)va_arg(pt, int);
```
|
The standard specifies that
Theva_argmacro expands to an expression that has the specified type and the value of the next argument in the call.
(C2011 7.16.1.1/2)
The fact that such an expression resulted from expansion of a macro has no bearing on how it can be used. In particular, when the type specified tova_argisint, the resultingint-type expression can certainly be cast to other integer types, provided thatva_arg()'s behavior is defined (roughly meaning thatintis compatible with the promoted type of the actual argument).
So yes, you can cast the result ofva_arg().
|
Can the intmax_t hold size_t maximum decimal number?
And what size type in printf have a biggest priority uintmax_t/intmax_t or size_t (ex. if i write printf("%zjd", x))?
|
Most likely not
Both are implementation specific, so it's not really possible to answer.
size_tis (usually) an unsigned integer holding the largest possible number of bits that will fit in a register on a given CPU. That's not exactly guaranteed in reality though, but I still haven't found an example where this isn't true.
intmax_tis a signed integer, meaning it will probably have the bits required to store any value that asize_tcan hold, but large values will not mean the same; the largest value that asize_tcan hold, is likely going to be a negative integer when interpreted as anintmax_t.
|
I am trying to read some strings and then print them into a matrix form.
```
int main(int argc, char **argv)
{
char *buffer[BUFFER_SIZE];
for(size_t i = 0; i < BUFFER_SIZE; i++)
{
scanf("%s",buffer[i]); /**This line is causing segment fault **/
}
for(size_t i = 0; i < BUFFER_SIZE; i++)
{
for(size_t j = 0; j < strnlen(buffer[i], MAX); j++ )
{
printf("%c ",buffer[i][j]);
}
printf("\n");
}
}
```
Any suggestion what I am missing here?
|
char *buffer[BUFFER_SIZE]is an array of character pointers. The way your code is now,buffer[i]is achar *that is uninitialized at the time youscanf("%s",buffer[i]). You need to allocate memory (malloc, perhaps) forscanfto store the string of characters prior to this point.
|
I created and allocated a double pointer like this:
```
int **a;
a = (int**)malloc(10 * sizeof(int *));
for (int i = 0; i < 10; i++)
*(a+i) = (int *)malloc(10 * sizeof(int));
```
And then I initialized it for example like this:
```
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
**a = 1;
(*a)++;
}
a++;
}
```
My problem and question is how can I save the address'es of my double pointer?At this moment I lost them and can't use them anymore.
|
Don't use explicit pointer arithmetic and dereferencing when array subscripting will do:
```
int rows = 10, cols = 10
int **a;
// don't cast the return value of malloc
a = malloc(rows * sizeof(*a));
for (int i = 0; i < rows; i++)
a[i] = malloc(cols * sizeof(**a));
...
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
a[i][j] = 1;
}
}
```
|
I have an MVC4 app that uses bootstrap
on one view I have
```
@Html.ListBoxFor(x=>x.ids,Model.OPtions,new {@class = "form-control",multiple ="multiple",id ="optionid",data_placeHolder ="Something}
```
Model.OPtionshave a string value that has special characters in it.
These are being stripped out
It is anIEmumerable<SelectListItem>
any ideas?
|
Have you tried to use HttpUtility.HtmlEncode as Luke Duddridge pointed out here?ASP MVC Razor encode special characters in input placeholder
|
I'm learning C and I am an absolute beginner. I'm trying to do an exercice but after several trials I can't solve it.
I have tocopy the arguments in*argv[]to an array of strings*states[]using awhileloopso each
```
printf("You've mentioned the state %s.\n", states[i]);
```
prints out the name of a state I should have input as an argument. I thinkthe only header I must use isstdio.h.
Thank you in advance for your help.
EDIT. So far I've only tried things like this
```
char *states[];
i = 1;
states[i] = argv[i];
if(argc > 1) {
while(i < argc){
printf("You've mentioned the state %s.\n", states[i]);
i++;
}
}
```
But, of course, I get an error because of thestates[i] = argv[i];statement.
|
You can do something like this:
```
char* states[argc];
int i = 0;
while (i < argc) {
strcpy(states[i], argv[i]);
}
```
You have to include
|
I'm trying to make a game program in C.
How to get a char or input without displaying and pausing the screen?
|
You mentioned you want to make a game in C.
Create your own window.
Capture and Process events.
This sounds a bit much for a beginner but actually it is not.
Use a library like SDL2 to help you with that.
Here is atutorial seriesthat walks you through some of the basics of game making.
|
Let's say I have a UInt16 made up of 2 UInt8s (upper bits and lower bits)
Is this statement correct?
As long as the value of the UInt16 is less than 256, all of the memory will exist in the lower bits and the upper bits will be 0
|
All of the set bits will be in the lower byte when the value is treated as a 16-bit unit, however if you cast the address of your variable to a char * you may find that the 'low byte' precedes the 'high byte' in memory.
This is called little-endian storage and is true, for example, on intel x86 based processors.
|
I understand the purpose of mutex in pthreads, but I often here that it is considered a bad practice to use mutex with a global variable as a shared resource (for example, like in the answer to this question:Mutex lock threads).
So, the questions:
Is it really that bad to put the shared resource as a global variable?If you have only 1 shared variable, like in the example, would it be considered ok to use a global variable, or still no?What is the better way to share the variables between the processes?
|
In general:
Global Variable are Evil:Global Variables Are Badon C2 WikiChapter 19: Global Variables Are EvilfromBetterEmbedded System Software
Yes, you have to create a variable in the main thread and pass the reference to other threads that have to use it, which is true even if you have only one shared variable.
|
I ran into a bug that I found somehow the memory will be filled with '0x6b' for each char by someone else. (I check the memory via printk, not ICE.) After a lot of debugging I found out that it was because I accidentally did kfree to the memory (it was allocated by kmalloc).
I'm curious about who fills the '0x6b' and trace the kfree code but can't find the code doing this. Is it a debugging mechanism of Linux kernel or there is some other reason?
(the env is kernel 4.9)
Thanks!
|
Is it a debugging mechanism of Linux kernel ...?
Yes, it's called "slab poisoning".
Here is the0x6bdeclared in the source for memory freeing:
https://elixir.free-electrons.com/linux/v4.9/source/include/linux/poison.h#L56
And here's a short blurb about it:
https://whatilearned2day.wordpress.com/2006/12/13/slab-poisoning/
|
I created a function to free an array in C, but I don't know
whether it is correct or not:
```
void dealloc_array(void *array[], int size) {
int i = 0;
for (i = 0; i < size; i++) {
if (array[i]) free(array[i]);
}
if (array) free(array);
}
```
I'm not sure whether I should executefree(array)at the end. Technically, we've already freed all the array elements, so we don't need to dofree(array).
Thanks for the help.
|
If you malloc the pointer as well as each element of the array you will need to free that pointer after your for loop.
For example:
```
int **array;
array = malloc(SIZE*sizeof(int*));
for(int ii = 0; ii < SIZE; ii++)
{
array[ii] = (int*)malloc(sizeof(int));
}
```
you will have to free each element and free array.
Essentially for every malloc/calloc you have, you must have a free
|
I created and allocated a double pointer like this:
```
int **a;
a = (int**)malloc(10 * sizeof(int *));
for (int i = 0; i < 10; i++)
*(a+i) = (int *)malloc(10 * sizeof(int));
```
And then I initialized it for example like this:
```
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
**a = 1;
(*a)++;
}
a++;
}
```
My problem and question is how can I save the address'es of my double pointer?At this moment I lost them and can't use them anymore.
|
Don't use explicit pointer arithmetic and dereferencing when array subscripting will do:
```
int rows = 10, cols = 10
int **a;
// don't cast the return value of malloc
a = malloc(rows * sizeof(*a));
for (int i = 0; i < rows; i++)
a[i] = malloc(cols * sizeof(**a));
...
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
a[i][j] = 1;
}
}
```
|
I have an MVC4 app that uses bootstrap
on one view I have
```
@Html.ListBoxFor(x=>x.ids,Model.OPtions,new {@class = "form-control",multiple ="multiple",id ="optionid",data_placeHolder ="Something}
```
Model.OPtionshave a string value that has special characters in it.
These are being stripped out
It is anIEmumerable<SelectListItem>
any ideas?
|
Have you tried to use HttpUtility.HtmlEncode as Luke Duddridge pointed out here?ASP MVC Razor encode special characters in input placeholder
|
I know that POSIX defines a set of functions that should be present in the compliant system. These includeread(),write(),printf(), and many other that we know as "libc" functions.
But does POSIX enforce a calling convention for them, or it is up to OS implementors to choose?
|
But does POSIX enforce a calling convention for them [...]?
No. POSIX aims to be portable. Calling conventions are heavily dependent on the architecture as they specify the way how stack and registers are used when calling subroutines. If POSIX made enforcements on certain calling conventions, it wouldn't be universally applicable any longer, or, alternatively, it would have to define calling conventions for each possible architecture, which is impossible.
|
I'm working on an assignment, but I'm having trouble with my code :
```
int is_ascii_match(const char c1[], const char c2[], char res[MAX_STRING_SIZE]) {
....
if (val_c1 == val_c2) {
strcpy(res, strcat(strcat(c1, '&'),c2));
}
else
return 0;
```
I'm getting an error :
Access violation reading location
Do I pass the parameters wrong or..?
|
strcatexpects a non-constchar*. You passed aconstthat's why compiler complained.
Also the second parameter would be"&". (Earlier you passed achar).
From standard §7.24.3.1
```
char *strcat(char * restrict s1, const char * restrict s2);
```
Thestrcatfunction appends a copy of the string pointed to bys2(including the terminating null character) to the end of the string
pointed to bys1.
Sos1will be modified (the first parameter) that's why it should be non-const.
|
I saw there are a lot of articles about memcpy but I can't find the solution for my problem. Can somebody see why the copy action doesn't work?
```
float MeanFilter(const volatile float *Array, volatile float Dist){
float Avg = 0.0; // Variable used to calculate the average distance value
float Sorted[MaxDistArray]; // Array used to contain the sorted array
printf("\n");
int j;
for(j = 0; j < 20; j++){
if(j == 10) printf("\n \t");
printf("%d: %f, ", j+1, Array[j]);
}
memcpy(Sorted, &Array[0], sizeof(float));
Sort(Sorted); // Sort the array of distances values
printf("\n");
for(j = 0; j < 20; j++){
if(j == 10) printf("\n \t");
printf("%d: %f, ", j+1, Sorted[j]);
}
```
|
Idd @Ronald that was part of the solution
```
memcpy(Sorted, Array, sizeof(float)*MaxDistArray);
```
thx!
|
I'm completely new to C and I'm trying to create a basic swap program, can someone please explain why the code below isn't working.
```
#include <stdio.h>
void swap (int *p1, int *p2);
int *temp = *p1;
*p1 = *p2;
*p2 = temp;
int main ()
{
int x = 10;
int y = 20;
int *p1 = &x, *p2 = &y;
swap (p1, p2);
printf ("x: %d, y: %d\n", x, y);
}
```
Thanks in advance.
|
int *temp = *p1;will not compile (this is aconstraint violationand must result in a compiler diagnostic): you are assigning anint(other than 0) to a pointer type. And that's not allowed.
Writeint temp = *p1;, fix the obvious typos in theswapfunction - give it a body! - and all will be well.
|
Is there a way to find which interface has been used to join an IPv6 multicast group, if the index used was 0 meaning that we leave to the kernel to choose which interface is suitable.
Can we get that information afterwards?
|
Does the IPV6_MULTICAST_IF socket option change after the join is complete? If not you'll have to look at the interface table and see which is the default, on windows this would be done with GetAdaptersAddresses, no idea for *nix.
|
Is there a kernel mode version of OpenProcess function?
Basically I want to get a process HANDLE from process ID.
Specifically, I want to get the HANDLE of System Process ID.
Thanks!
|
If you are in an arbitrary system thread you can use ZwCurrentProcess(), otherwise you will need to figure out the ID of a system thread somehow and use ZwOpenProcess.
You might also look to see if there is a way to convert the result of PsInitialSystemProcess to a process handle (or maybe PsInitialSystemProcess is what you are really after).
|
I'm completely new to C and I'm trying to create a basic swap program, can someone please explain why the code below isn't working.
```
#include <stdio.h>
void swap (int *p1, int *p2);
int *temp = *p1;
*p1 = *p2;
*p2 = temp;
int main ()
{
int x = 10;
int y = 20;
int *p1 = &x, *p2 = &y;
swap (p1, p2);
printf ("x: %d, y: %d\n", x, y);
}
```
Thanks in advance.
|
int *temp = *p1;will not compile (this is aconstraint violationand must result in a compiler diagnostic): you are assigning anint(other than 0) to a pointer type. And that's not allowed.
Writeint temp = *p1;, fix the obvious typos in theswapfunction - give it a body! - and all will be well.
|
Is there a way to find which interface has been used to join an IPv6 multicast group, if the index used was 0 meaning that we leave to the kernel to choose which interface is suitable.
Can we get that information afterwards?
|
Does the IPV6_MULTICAST_IF socket option change after the join is complete? If not you'll have to look at the interface table and see which is the default, on windows this would be done with GetAdaptersAddresses, no idea for *nix.
|
Is there a kernel mode version of OpenProcess function?
Basically I want to get a process HANDLE from process ID.
Specifically, I want to get the HANDLE of System Process ID.
Thanks!
|
If you are in an arbitrary system thread you can use ZwCurrentProcess(), otherwise you will need to figure out the ID of a system thread somehow and use ZwOpenProcess.
You might also look to see if there is a way to convert the result of PsInitialSystemProcess to a process handle (or maybe PsInitialSystemProcess is what you are really after).
|
If I have source code filesmain.c,library.c,library.h, etc. how would I go about setting the input text files to act as console commands likemain input1.txt input2.txt? Can this be done at all or must it be done post-compilation?
|
```
program: main.c library.c
gcc -o program $<
.PHONY: run
run: program input1.txt input2.txt.
./program input1.txt input2.txt
```
Basically, you treat them like dependencies for running the program. In the above example,make runwill run the program and compile it if needed.
|
Is there something likestd::reallocbut do nothing if it fails to expand the existing memory (of course it will let you know it failed)?
I mean truly expand in place. Not copy to a newly created memory chunk.
|
Contrary to what other answers say, the function you needcouldbe provided by the C standard ibrary. It isn't for some reason or other.
It was considered for an adition to the C standard, see e.g.http://www.open-std.org/JTC1/SC22/wg14/www/docs/n1527.pdf(search for try_realloc). I don't know if the C committee is still pursuing this.
Bottom line, there's no such function as of now.
|
I am creating a chat in C (Should work on Ubuntu 16.04) based on the IRC protocol. I already create the client.c and the server.c. The chat is working ok and a client can send a message to the server and the server re-send the message to one or all clients. The problem is that I dont know how send a file from a client to another client.
It should be something like the client 1 send part of the file to the server and the server re-send it to the client 2 and so on. The problem is that I dont know how to do it because the server must continue attending the clients while it is sending and receiving the file. Thank you
|
select in the server main loop was all i need
|
I am new at GTK and started out using Glade to design a UI. But whenever I run my app, I must keep the Glade file in the same directory as the executable. I would like to distribute the Glade file in a compiled form, same as the source code. Is this possible?
|
Yes, that's possible. Give a look to theGResourcedocumentation. Its main use is to embed resources like ui files, icons, etc. in the main binary.
|
I'm having troubles writing char arrays of '1' and '0' 's as binary in a file.
Here is an example of what I'm trying to do :
```
int main(){
FILE * file;
file = fopen("file" , "w+b");
char buffer[8] = "11001100"; // 8 bits-> 1 byte to write
fwrite(buffer,1,8,file);
fclose(file);
return 0;
}
```
The problem is it writes itself as text in my file (8 bytes written), not as binary/just 1 byte.
What am I doing wrong ?
Thanks in advance for your help.
|
You can use the0bprefix i think...GNU doc
0bsays you are writing a byte.
If you write somethink like this:
```
int main(){
FILE * file;
file = fopen("file" , "w+b");
char c;
c = 0b11001100
fwrite(&c,1,1,file);
fclose(file);
return 0;
}
```
|
I am new at GTK and started out using Glade to design a UI. But whenever I run my app, I must keep the Glade file in the same directory as the executable. I would like to distribute the Glade file in a compiled form, same as the source code. Is this possible?
|
Yes, that's possible. Give a look to theGResourcedocumentation. Its main use is to embed resources like ui files, icons, etc. in the main binary.
|
Working on the POSIX signal emulation forJehanne, I realized that thestandarddoes not explain what happens to the existing children of a process that callssetsid().
I wonder if they remain in the previous session and process group or they will follow the parent in the new session.
And, if they remain in the previous session/group, will the parent still receive SIGCHLD when they exit?
|
Nothing; they retain their session. And SIGCHLD has nothing to do with sessions, just parent-child relationship.
|
As a server, I want to read from a non-blocking client socket and then write to a file.
According to the man page for sendfile, if errno is set to EAGAIN, then this only signals that, if theoutputfile descriptor is set to be non-blocking, then a call to sendfile would block.
That is, the underlying call that sendfile makes to write would block.
Is there anyway to use sendfile so that errno is EAGAIN if reading would block?
|
Certainly.
Using theselect()library function with your read descriptor, you can check forEWOULDBLOCKviaerrno. If it is set, then the read would block.
You cannot see if the read would block by checking something on yoursendfile()call.
|
Does anyone know the Ethertype number of UDP and TCP? I know IPv4 is 0x0800 and IPv6 are 0x86dd. I'm writing a program that gives me information about a packet based on the type of packet it is.
|
Ethernet frame has three parts source,destination MAC address and Ethertypes.
Ethertypes show us how Layer-2 interacts with Layer-3 in the OSI model. As you look up the model, At Layer-3, within IPv4 there is a protocol field to determine if it is TCP, UDP, ICMP or something else. At Layer-4, within TCP and UDP, we have the port to determine which application should handle the packet.
So TCP and UDP doesn't have Ethertypes, instead they have protocol numbers. The following are the protocol numbers for UDP and TCP :
0x11 for User Datagram Protocol (UDP)
0x06 for Transfer Control Protocol (TCP)
Reference
|
As a server, I want to read from a non-blocking client socket and then write to a file.
According to the man page for sendfile, if errno is set to EAGAIN, then this only signals that, if theoutputfile descriptor is set to be non-blocking, then a call to sendfile would block.
That is, the underlying call that sendfile makes to write would block.
Is there anyway to use sendfile so that errno is EAGAIN if reading would block?
|
Certainly.
Using theselect()library function with your read descriptor, you can check forEWOULDBLOCKviaerrno. If it is set, then the read would block.
You cannot see if the read would block by checking something on yoursendfile()call.
|
Does anyone know the Ethertype number of UDP and TCP? I know IPv4 is 0x0800 and IPv6 are 0x86dd. I'm writing a program that gives me information about a packet based on the type of packet it is.
|
Ethernet frame has three parts source,destination MAC address and Ethertypes.
Ethertypes show us how Layer-2 interacts with Layer-3 in the OSI model. As you look up the model, At Layer-3, within IPv4 there is a protocol field to determine if it is TCP, UDP, ICMP or something else. At Layer-4, within TCP and UDP, we have the port to determine which application should handle the packet.
So TCP and UDP doesn't have Ethertypes, instead they have protocol numbers. The following are the protocol numbers for UDP and TCP :
0x11 for User Datagram Protocol (UDP)
0x06 for Transfer Control Protocol (TCP)
Reference
|
This question popped up in a quiz:
Replace ‘Z’ with the proper number to set the FILE pointer ‘fp’ to the last byte of the file:
```
fseek( fp, Z, SEEK_END );
```
My answer was -1 because to me, it seemed natural that being at a certain byte meant being at a position such that appending to that file would overwrite that byte keep storing other bytes if any. The teacher insists on 0. I would appreciate if you could explain.
|
-1 appears to be correct. I just tried it, and anfgetcafterfseek(f, -1, SEEK_END)produced the last character of the file. Seeking to 0 relative toSEEK_ENDresulted infgetcreturningEOF.
Clearly pointing to the last byte of a file is different from pointing to the end of the file. Furthermore, if there is any ambiguity in terminology, it is a failure of the test, not of the student. If the student has demonstrated the expected knowledge, they should receive credit.
|
This question already has answers here:usage of "\" in C?(3 answers)Closed5 years ago.
I can't apprehend the use of backslash in this piece of code, does it act as an operator in this scenario ?
```
#define foreach(item, array) \
for(int keep = 1, \
count = 0,\
size = sizeof (array) / sizeof *(array); \
keep && count != size; \
keep = !keep, count++) \
for(item = (array) + count; keep; keep = !keep)
```
|
It means the same as if you had written it on a single line.
When writing a#define, you can't use line breaks in the middle of a definition. But, putting it all on a single line would hamper readability. Hence, this is what is done usually.
Yes, it works for code as well, because the C specification states:
Each instance of a backslash character () immediately followed by a new-line character is deleted, splicing physical source lines to
form logical source lines.
|
i'm trying to read variables from a txt file.
The file .txt is like:
```
john 10
mark 230
peter 1
```
I would like to transfer and save this values in an array, for example array[0] = 10, array[1] = 230 etc without minding of names. I pasted my code below and I would like to know how can i edit it using this code below
```
int conf[4], i = 0, c;
FILE *file_conf;
file_conf = fopen("conf.txt", "r");
if(file_conf == NULL){
fprintf(stderr, "Error\n");
exit(EXIT_FAILURE);
} else {
while((c = fgetc(file_conf)) != EOF) {
fscanf(file_conf, "%d", &conf[i]);
printf("%d\n", conf[i]);
i++;
}
}
```
|
You should not be usingfgetc()at all--that gets a single character. Instead, add the name format to yourfscanf(), something like this:
```
char name[100];
fscanf(file_conf, "%s %d", name, &conf[i]);
```
|
I am trying to learn socket programming. So my question is that if you fork a child on the client after connecting to a socket i.e. after doing the connect call. Then can you read and write independently using socket descriptor in the child and the parent? Server only knows one socket. So if you are reading fast at the child than at the parent. Will there be data loss at the parent?
|
Yes. If two processes try to act on the same connection, they will compete.
Forking will duplicate the connection's file descriptor (as withdup/dup2/dup3), but those two filedescriptors will just be two counted references to the same connection.
Practically that means most fd-taking syscalls (read(),write(),...) will get through to the shared target file (the actual connection), howeverclose()calls will only decrement the ref count and will only initiate a connection shutdown (as with theshutdown()syscall) when the refcount becomes0.
|
I have a module that is hookingap_hook_child_init. From that callback I would like to obtain the directory where the main apache2.conf file lives (or the full path to that file, I'll parse out the directory).
That callback takes aserver_recstruct and aapr_poot_tstruct.server_rechas apathmember, but it is null.
|
You can't find this directly, and of course "apache2.conf" may not exist at all. This file is a debian-ism.
However, one option you have is to:
Find a directive commonly present in this config file or whatever substitutes you'd like treat the sameAdd the directive to your module with the same definition as the core moduleWhen you get control in the callback for handling the directive, look at cmd->directive->fname and save the path away in a global variable.
Multiple modules can share the same directive name and they all get called to process it.
|
I have some C code that uses the inb instruction in inline assembly. I heard that inb takes operands that have a size of 8-bits. AL and DL are 8 bits, so why won't this work?
```
__asm__ __volatile__("inb %al, %dl");
```
It says "Operand type mismatch for in". If it matters, I have the ".code16gcc" at the top.
All help is appreciated.
|
Two things: In AT&T-style assembly, the destination operand is last, and the port number is 16 bits even when the data is 8 bits. So:
```
inb %dx, %al
```
|
I have the simple code witch get password by getpass:
```
if (!(pass = getpass("Enter password:\n"))) {
perror("getpass failed");
return -1;
}
```
Also I have a signal handler witch exit program.
If signal was caught at the time of getting password from terminal, program stops, but all provided by user characters appears on bash prompt.
Code of signal handler:
```
void handle (int sig) {
printf("Time for password entering expired!\n");
/* Enable echo on terminal after aborted getpass*/
system("stty echo");
exit(-1);
}
```
How can I make bash prompt clear after interrupt program by signal?
|
Using oftermiosresolved problem.
|
This question already has answers here:Why cast unused return values to void?(10 answers)Need for prefixing a function with (void)(6 answers)Closed5 years ago.
In our source code there are function calls like these where the return value gets cast tovoid:
```
(void) pthread_mutex_lock(&mutex);
```
What's the purpose of this?
|
This is not a functionality or anything. It is just an easy way to document or show the future coders or maintainers that the return value is ignored and the coder was aware of that. Nothing else except this.
Some function's (applyingwarn_unused_resultattribute for gcc) enforce warning on ignoring implicitly the return value - this warning can be suppressed usingvoidcasting. (On some compiler versions(void)cast alone won't do - but that's different story)
|
I have a file and I want to make a backup file, with the same name as file but with "aux" at the end. How do I do this? I tried:
```
char *nameFile, *nameAux;
char *aux = aux;
nameAux = nameFile + aux;
```
Which didn't work.. nameFile is given to me by the user, and it's right because I can open/ceate the file with nameFile
|
You can't just "add" C strings. effectively you've summed pointers.
SeeHow do I concatenate const/literal strings in C?
|
What is the purpose of the usagethread##_typein this code snippet?
I understand that underscoret (_t)is used as a convention for naming to identify types, as is underscore type(_type), often intypedefstatements. I also understand##inmacrosindicate concatenation. Does_typehas any purpose other than this? (like the usage of double underscore__FILE__)?
```
#define THREAD_TYPE(thread)
typedef struct \
{ \
pthread_t pthread; \
int err; \
} thread##_type;
```
|
_typehas no special meaning in C. This code is simply decorating the name in a way the author chose, nothing more.
|
I want to configure variable accept_local in /proc/sys/net/ipv4// dynamically. Instead of using file operation, is there any system call that I can use to configure this.
|
Writing values to filesissyscalls, so, if you want to achieve that through Linux syscalls:
fd = open("/proc/sys/net/ipv4/accept_local", O_WRONLY)that file (first syscall)write(fd, "1", 1)to that (second syscall)close(fd)the file handle (third syscall).
Voila, network configuration done through three syscalls.
PS: Your question reeks very much of the famousXY Problem.
|
This question already has answers here:Why cast unused return values to void?(10 answers)Need for prefixing a function with (void)(6 answers)Closed5 years ago.
In our source code there are function calls like these where the return value gets cast tovoid:
```
(void) pthread_mutex_lock(&mutex);
```
What's the purpose of this?
|
This is not a functionality or anything. It is just an easy way to document or show the future coders or maintainers that the return value is ignored and the coder was aware of that. Nothing else except this.
Some function's (applyingwarn_unused_resultattribute for gcc) enforce warning on ignoring implicitly the return value - this warning can be suppressed usingvoidcasting. (On some compiler versions(void)cast alone won't do - but that's different story)
|
I have a file and I want to make a backup file, with the same name as file but with "aux" at the end. How do I do this? I tried:
```
char *nameFile, *nameAux;
char *aux = aux;
nameAux = nameFile + aux;
```
Which didn't work.. nameFile is given to me by the user, and it's right because I can open/ceate the file with nameFile
|
You can't just "add" C strings. effectively you've summed pointers.
SeeHow do I concatenate const/literal strings in C?
|
What is the purpose of the usagethread##_typein this code snippet?
I understand that underscoret (_t)is used as a convention for naming to identify types, as is underscore type(_type), often intypedefstatements. I also understand##inmacrosindicate concatenation. Does_typehas any purpose other than this? (like the usage of double underscore__FILE__)?
```
#define THREAD_TYPE(thread)
typedef struct \
{ \
pthread_t pthread; \
int err; \
} thread##_type;
```
|
_typehas no special meaning in C. This code is simply decorating the name in a way the author chose, nothing more.
|
I want to configure variable accept_local in /proc/sys/net/ipv4// dynamically. Instead of using file operation, is there any system call that I can use to configure this.
|
Writing values to filesissyscalls, so, if you want to achieve that through Linux syscalls:
fd = open("/proc/sys/net/ipv4/accept_local", O_WRONLY)that file (first syscall)write(fd, "1", 1)to that (second syscall)close(fd)the file handle (third syscall).
Voila, network configuration done through three syscalls.
PS: Your question reeks very much of the famousXY Problem.
|
When I replace the absolute path ofMINGW-HOMEwith a Relative Path, the C code compiles and runs with a warningToolchain "MinGW GCC" is not detected. And when i try to debug, i get the following error message.Cannot run program "gdb".
I only get this problem when the path to theMINGW-HOMEis written as a relative. I am also very sure that the relative path is correct because, the program can compile and run without an error, but just doesn't debug.
Here is the setting with the absolute paths:
Here is the setting with the relative paths and the warning:
Here is the error message gotten while trying to debug
|
Use astypeDirectoryinstead ofStringand start theValuewith:
for relative to the workspace:${workspace_loc}/../../.....for relative to the projectCUR:${workspace_loc:/CUR}/../.....
|
Can a string constant like"foo" "\x01" "bar"be written as a single string literal (while keeping the hexadecimal notation)? With"foo\x01bar"the escape sequence seems to be interpreted as\x01basince I get the warning "hex escape sequence out of range."
|
"foo" "\x01" "bar"isa string literal.
The C standard states that a hexadecimal escape sequence is the longest sequence of characters that can constitute the escape sequence. Without the explicit concatenation (which is the common workaround to this problem), the compiler parses\x01bawhich is obviously out of range.
|
I have my ZC706 board with dual arm cortex 32bit one. I am trying to run an algorithm over it, as a part of the code it has floating point values.
```
uint32_t int Ts = 69912;
float Ts_pico;
Ts_pico = 20*(10^-12)*Ts;
printf("Time stamp in picoseconds is %f", Ts_pico);
```
And it prints a value 4272595456.000000 instead of 1.39824*(10^-6)
So I tested by printing
```
printf("The float point value is %f", 1.39824);
```
It was fine printing out the following value.
Next, when i tested by printing
```
double f = 10^-6;
printf("The flloat point value is %f", f);
```
The value it has printed is -14401872.000000
How can I solve the issue with floating point values?
|
Didn't you want10e-12rather10^-12?
10e-12is afloating pointdoubleconstant, although do note that1e-12is10raised to the-12thpower. Your^is an abuse of the XOR operator.
|
For example,a.h
```
static inline void asdf(int a) {}
```
b.h
```
static inline void asdf(int a) {}
```
is this ok? will there be any conflicts?
|
Technically, yes, it's ok. static functions are only visible in the same compilation unit.
Practically, no, it's not ok. It makes your code hard to read and if I had to maintain your code later I'd hate you for it. Either because the functions do different things or because they diverge over time because someone fixed a bug in one of them and forgot the other.
|
I have compiled following program usinggcc prog.c -Wall -Wextra -std=gnu11 -pedanticcommand onGCCcompiler. I wondered, it is working fine without any warnings or errors.
```
#include <stdio.h>
int main(void)
{
for (int i = 0; i == 0; i++)
{
printf("%d\n", i);
long int i = 1; // Why doesn't redeclaration error?
printf("%ld\n", i);
}
}
```
Why compiler doesn't generate redeclaration variableierror?
|
From standard §6.8.5.5 (N1570)
An iteration statement is a block whose scope is a strict subset of
the scope of its enclosing block.The loop body is also a block whose
scope is a strict subset of the scope of the iteration statement.
Emphasis added
|
How can I return a string constant from a call toffi:c-inline?
I've tried variations of the following without success (ORGANIZATIONis a constant defined in constants.h):
```
(ffi:clines "#include \"./constants.h\"")
(ffi:c-inline () () :string "ORGANIZATION" :one-liner t)
```
The example above results in the following compiler error:
Unknown representation type :STRING
|
Use:cstringinstead of:string:
constants.h:
```
#define ORGANIZATION "foobar"
```
ecl.lsp:
```
(ffi:clines "#include \"./constants.h\"")
(defun myfun ()
(ffi:c-inline () () :cstring "ORGANIZATION" :one-liner t))
```
From ecl prompt:
```
> (compile-file "ecl.lsp" :load t)
...
> (myfun)
"foobar"
>
```
Reference:https://ecl.common-lisp.dev/static/manual/Foreign-Function-Interface.html#Primitive-Types
|
(New to C and programming in general.)
When I run this small program to prompt a user to enter 1 or 2, I want to check if the input is correct, so I ran a while loop that was supposed to run until the correct input is given. But even when I type 1 or 2 (doesn't matter whether it's from the beginning or after giving invalid input), the error message keeps printing.
Am I supposed to have a break in the while loop? If so, is there a more efficient/"less code" way of checking user input?
```
int main(void) {
char c;
printf("Press '1' or Press '2': ");
c = getchar();
while ((c != '1') || (c != '2')) {
printf("ERROR: Invalid Input. Please try again: ");
c = getchar();
}
return 0;
}
```
Thanks in advance.
|
You need to use&&instead of||. Think: if I enter 1, then(1 != 1)isfalse, but(1 != 2)istrue, then(false || true) == true. Using&&should fix your problem.
|
I tried code below, but the results aren't correct. I think that something with size of buffer can be implemented in a wrong way.
```
int f(int* as) {
*as = read(STDIN_FILENO, as, sizeof(int));
} //i print 123
int s;
f(&s);
printf("%d",s); // prints 4
```
|
Two things that prevent the program to give the result you expect
1) usingreadto read from standard input (characters) and store that into a (binary) integer
2) storing the result ofreadinto that same integer, overwriting the (wrong) value stored in 1)
Have a look atscanforfgets(atoi...), to read into a character array (string),thenconvert the characters read into a binary number, for instance
```
char str[20];
fgets(str, 20, stdin);
int s = atoi(str);
```
readversion
```
char str[20];
ssize_t nread = read(STDIN_FILENO, str, 20);
int s = atoi(str);
```
Seewhat an integer is,
|
```
int *a=500;
*a=3;
printf("%d",*a);
```
look at above code.
I want to set the address 500 of memory to 3. but when I compile this code I get an error(segmentation fault). what is the problem?
|
This is invalid:
```
int *a=500;
```
You can't just assign an arbitrary address to a pointer variable and expect that it is pointing anyplace useful. You can only do something like this on embedded platforms that have well-defined addresses for specific devices.
You can only assign the address of an exiting variable or an address returned by a memory allocation function likemalloc:
```
int b;
int *a = &b; // valid
int *c = malloc(sizeof(int)); // valid
int *d = 500; // not valid
```
|
I want to allocate an array inside of a function and to be able to use the pointer to that array outside of it as well. I don't know what's wrong with my code
```
#include <stdio.h>
#include <stdlib.h>
void alloc_array (int **v, int n)
{
*v=(int *)calloc(n,sizeof(int));
printf ("the address of the array is %p",v);
}
void display_pointer (int *v)
{
printf ("\n%p",v);
}
int main()
{
int *v;
alloc_array(&v,3);
display_pointer(v);
return 0;
}
```
I would expect to get the same address in bothprintfs, but that is not the case. What is my mistake?
|
```
void alloc_array (int **v, int n)
{
*v = calloc(n,sizeof(int));
printf("the address of the array is %p", *v);
// ----^
}
```
Note the additional star in myprintfcall.
Also, don't cast the return value ofmalloc/calloc.
|
In need to craft a string with the following format and place it into a single buffer[1000]. Note that \x00 is the null terminator.
```
@/foo\x00ACTION=add\x00SUBSYSTEM=block\x00DEVPATH=/devices/platform/goldfish_mmc.0\x00MAJOR=command\x00MINOR=1\x00DEVTYPE=harder\x00PARTN=1
```
So in essence I need to pack following null terminated strings into a single buffer
```
@/foo
ACTION=add
SUBSYSTEM=block
DEVPATH=/devices/platform/goldfish_mmc.0
MAJOR=command
MINOR=1
DEVTYPE=harder
PARTN=1
```
How might I go about doing this?
|
You'll need to copy each string in one at a time, keeping track of where the last copy stopped and starting just after that for the next one.
```
char *p = buffer;
strcpy(p, "@/foo");
p += strlen(p) + 1;
strcpy(p, "ACTION=add");
p += strlen(p) + 1;
...
```
|
(New to C and programming in general.)
When I run this small program to prompt a user to enter 1 or 2, I want to check if the input is correct, so I ran a while loop that was supposed to run until the correct input is given. But even when I type 1 or 2 (doesn't matter whether it's from the beginning or after giving invalid input), the error message keeps printing.
Am I supposed to have a break in the while loop? If so, is there a more efficient/"less code" way of checking user input?
```
int main(void) {
char c;
printf("Press '1' or Press '2': ");
c = getchar();
while ((c != '1') || (c != '2')) {
printf("ERROR: Invalid Input. Please try again: ");
c = getchar();
}
return 0;
}
```
Thanks in advance.
|
You need to use&&instead of||. Think: if I enter 1, then(1 != 1)isfalse, but(1 != 2)istrue, then(false || true) == true. Using&&should fix your problem.
|
I tried code below, but the results aren't correct. I think that something with size of buffer can be implemented in a wrong way.
```
int f(int* as) {
*as = read(STDIN_FILENO, as, sizeof(int));
} //i print 123
int s;
f(&s);
printf("%d",s); // prints 4
```
|
Two things that prevent the program to give the result you expect
1) usingreadto read from standard input (characters) and store that into a (binary) integer
2) storing the result ofreadinto that same integer, overwriting the (wrong) value stored in 1)
Have a look atscanforfgets(atoi...), to read into a character array (string),thenconvert the characters read into a binary number, for instance
```
char str[20];
fgets(str, 20, stdin);
int s = atoi(str);
```
readversion
```
char str[20];
ssize_t nread = read(STDIN_FILENO, str, 20);
int s = atoi(str);
```
Seewhat an integer is,
|
```
int *a=500;
*a=3;
printf("%d",*a);
```
look at above code.
I want to set the address 500 of memory to 3. but when I compile this code I get an error(segmentation fault). what is the problem?
|
This is invalid:
```
int *a=500;
```
You can't just assign an arbitrary address to a pointer variable and expect that it is pointing anyplace useful. You can only do something like this on embedded platforms that have well-defined addresses for specific devices.
You can only assign the address of an exiting variable or an address returned by a memory allocation function likemalloc:
```
int b;
int *a = &b; // valid
int *c = malloc(sizeof(int)); // valid
int *d = 500; // not valid
```
|
I want to allocate an array inside of a function and to be able to use the pointer to that array outside of it as well. I don't know what's wrong with my code
```
#include <stdio.h>
#include <stdlib.h>
void alloc_array (int **v, int n)
{
*v=(int *)calloc(n,sizeof(int));
printf ("the address of the array is %p",v);
}
void display_pointer (int *v)
{
printf ("\n%p",v);
}
int main()
{
int *v;
alloc_array(&v,3);
display_pointer(v);
return 0;
}
```
I would expect to get the same address in bothprintfs, but that is not the case. What is my mistake?
|
```
void alloc_array (int **v, int n)
{
*v = calloc(n,sizeof(int));
printf("the address of the array is %p", *v);
// ----^
}
```
Note the additional star in myprintfcall.
Also, don't cast the return value ofmalloc/calloc.
|
In need to craft a string with the following format and place it into a single buffer[1000]. Note that \x00 is the null terminator.
```
@/foo\x00ACTION=add\x00SUBSYSTEM=block\x00DEVPATH=/devices/platform/goldfish_mmc.0\x00MAJOR=command\x00MINOR=1\x00DEVTYPE=harder\x00PARTN=1
```
So in essence I need to pack following null terminated strings into a single buffer
```
@/foo
ACTION=add
SUBSYSTEM=block
DEVPATH=/devices/platform/goldfish_mmc.0
MAJOR=command
MINOR=1
DEVTYPE=harder
PARTN=1
```
How might I go about doing this?
|
You'll need to copy each string in one at a time, keeping track of where the last copy stopped and starting just after that for the next one.
```
char *p = buffer;
strcpy(p, "@/foo");
p += strlen(p) + 1;
strcpy(p, "ACTION=add");
p += strlen(p) + 1;
...
```
|
This one is simple, I have an array of chars and I want to print it but I want to have a space between each individiual member of array, is this possible with printf? Or do I have to prepare a separate function?
Example:
```
char array[]="hello";
printf ("%s", array);
```
Output:
```
h e l l o
```
|
Since you don't want an extra space after the final character:
```
char *tmp = array;
if (*tmp) {
putchar(*tmp++);
while (*tmp) {
putchar(' ');
putchar(*tmp++);
}
}
```
Or turn it into a function:
```
void put_with_spaces(const char *s, FILE *fp)
{
if (!*s)
return;
fputc(*s++, fp);
while (*s) {
fputc(' ', fp);
fputc(*s++, fp);
}
}
```
|
My target is to compare two u_long timestamps, delivered by a GPS device. A long integer like 16290212 has the following structure:
hhmmssµµ
The following code snippet shows an approach how to parse a long integer to an integer array. But I think this is not very efficient. What would be the quickest way to compare two timestamps? I would love to use an UNIX timestamp, but it is not possible in this context.
```
u_long timestamp_old = 16290212;
u_long base = 1000000;
/* arr[0]: hours
* arr[1]: minutes
* arr[2]: seconds
* arr[3]: miliseconds */
int arr[4];
int i=0;
// parse timestamp_old
while(base >= 1)
{
arr[i++] = (timestamp_old / base);
timestamp_old = (timestamp_old % base);
base /= 100;
}
```
|
Your timestamps areu_longs; compare them the same way you compare any 2u_longs, something like<.
|
Man page offcntltell its used for manipulating file descriptors. But this name is not easy to remember. Knowing its full name will help in remember this system call name and its use. I tried to find on internet but could not get anything except man pages.
Please someone tell what is full name or origin of name of fcntl.
|
From POSIX, it isFileControl:
NAMEfcntl-filecontrol
There is a related system call,ioctl, i.e.Input-OutputControl. The difference between the 2 is thatfcntlmodifies the file descriptor / file description, whereasioctlcontrols behaviour of the input/output device behind the file description.
|
I am trying to translate some C code to Go and I'm wondering if there is a Go equivalent to the following linked list types:
```
typedef struct TOKENLIST {
token item;
struct TOKENLIST *next;
} token_list_elt, *token_list;
```
So far it appears that I would have to create both types separately like this:
```
type token_list struct {
item token
next *token_list
}
type token_list_elt struct {
item token
next *token_list_elt
}
```
This is not such a big deal for this example, but there are lots linked list types like these I need to translate and some of them have many aliases and/or struct fields.
|
But why not use it like this:
```
type linkedList struct {
item token
next *linkedList
}
...
tokenList := linkedList{}
tokenListElt := linkedList{}
```
Are different struct types so important?
|
I am working on an implementation of named pipes client/server for school. I have asked my teacher what happens if i use unlink while either of the pipes end is still opened. He had no answer for me.
Anyone know?
|
Nothing in particular happens, except the name is removed from the file system so no future processes can open the same named pipe.
The processes that has the pipe open will continue as normal.
|
My target is to compare two u_long timestamps, delivered by a GPS device. A long integer like 16290212 has the following structure:
hhmmssµµ
The following code snippet shows an approach how to parse a long integer to an integer array. But I think this is not very efficient. What would be the quickest way to compare two timestamps? I would love to use an UNIX timestamp, but it is not possible in this context.
```
u_long timestamp_old = 16290212;
u_long base = 1000000;
/* arr[0]: hours
* arr[1]: minutes
* arr[2]: seconds
* arr[3]: miliseconds */
int arr[4];
int i=0;
// parse timestamp_old
while(base >= 1)
{
arr[i++] = (timestamp_old / base);
timestamp_old = (timestamp_old % base);
base /= 100;
}
```
|
Your timestamps areu_longs; compare them the same way you compare any 2u_longs, something like<.
|
Man page offcntltell its used for manipulating file descriptors. But this name is not easy to remember. Knowing its full name will help in remember this system call name and its use. I tried to find on internet but could not get anything except man pages.
Please someone tell what is full name or origin of name of fcntl.
|
From POSIX, it isFileControl:
NAMEfcntl-filecontrol
There is a related system call,ioctl, i.e.Input-OutputControl. The difference between the 2 is thatfcntlmodifies the file descriptor / file description, whereasioctlcontrols behaviour of the input/output device behind the file description.
|
I am trying to runlsusing system calls in C with more than one argument, for example -l -a. The arguments and their number is changing depending on the user input. The input is concatenated "-l" + "-a" == "-l -a". The code I'm using is:
```
execlp("ls","ls",arguments,NULL) //arguments = "-l -a"
```
The user input is from Terminal:
```
-l
-a
```
|
if you want to executes more than one argument , then you should useexecvp()instead ofexeclp.
```
#include<stdio.h>
#include <unistd.h>
int main(int argc,char *argv[])
{
execvp(argv[1],argv+1);// argv+1 means whatever arguments after argv[1] it will take & executes it
return 0;
}
```
for e.g your input like that
```
xyz@xyz-PC:~$ ./a.out ps -el
```
I hope it helps.
|
```
#include <stdio.h>
#include <stdlib.h>
char pointer();
void main() {
char*name = "Paz Leviim", **p_name = &name;
*p_name = pointer();
printf("Now it's %s", *p_name);
getchar();
}
char pointer() {
char name_to_main[100];
printf("The value now is Paz Leviim\nPlease set value:");
scanf_s("%[^\n]%*c", &name_to_main,100);
return name_to_main;
}
```
How can I return the value of variable name_to_main to the pointer *p_name?
|
```
#include <stdio.h>
#include <stdlib.h>
char*pointer(char*now);
void main() {
char*name = "Paz Leviim", **p_name = &name;
*p_name = pointer(*p_name);
printf("Now it's %s", *p_name);
getchar();
}
char*pointer(char*now) {
static char name_to_main[100];
printf("The value now is %s\nPlease set value:",now);
scanf_s("%[^\n]%*c", &name_to_main,100);
return name_to_main;
}
```
Now all working :)
|
```
// Sting for the Name
extern const PROGMEM char name[];
//Data structure of the Heap
typedef struct
{
AllocStrategies strategy;
uint16_t size;
MemAddr start;
MemDriver* driver;
const PROGMEM char name[];
}Heap;
```
expected '=', ',', ';', 'asm' or '__ attribute__' before 'char'
Why do i get this error message twice?
|
You forgot to include a file:
```
#include <avr/pgmspace.h>
```
ThePROGMEMattribute that allows you to allocate aconstvariable in program space is defined there.
You are getting this error message twice because you are usingPROGMEMtwice.
|
This question already has answers here:Compiler warning - suggest parentheses around assignment used as truth value(3 answers)Closed5 years ago.
While looking into a piece of code, I saw this line:
```
if ((b = a)) { /* statements */ }
```
Reading the context, I know its intention is like this:
```
b = a;
if (b != 0) { /* statements */ }
```
I know the two lines above can be simplified into the first code block, but why are the two pair of parentheses? Wouldn't that seem redundant? I think this is totally OK:
```
if (b = a) { /* statements */ }
```
|
Usually one do that to avoid the warning from the compiler, that the assignment is to be (then) evaluated as a condition (in case the developer missed an=in==)
warning: suggest parentheses around assignment used as truth value
Something more indicative,
```
int c = !!(b = a); // condition
if (!!(b = a)) {
```
|
This question already has answers here:How can I print a string to the console at specific coordinates in C++?(7 answers)Closed5 years ago.
Now, I can get a direction txt file from my code:
```
down
down
right
right
up
.
.
.
```
I want to ask how can I display the walking process on linux terminal.
For instance, I want to use a dot representing a mouse which can execute the direction above.
|
nCurses is the best solution. You can het help with the built-in manual:
```
man -s 3 ncurses
```
A simpler way to do so is to useANSI CSI escape sequences:
```
printf("\x1B[A"); // Up
printf("\x1B[B"); // Down
printf("\x1B[C"); // Left
printf("\x1B[D"); // Right
```
To move up and print a dot:
```
printf("\x1B[A.");
```
|
Using gprof 2.28 and gcc 6.3.0 in Ubuntu 17.04 on a variety of sample programs I get empty output for every category. If I run gprof -i on one example program I get:
```
1 histogram record
2 call-graph records
0 basic-block count records
```
My compilation looks something like this:
```
cc -g -c sem_test.c -pg
cc -o sem_test sem_test.o -lpthread -pg
```
Or this:
```
gcc -g3 -O0 -Wall -std=gnu99 -pg -fprofile-arcs -fno-inline -fno-reorder-functions sem_test.c -o sem_test -lpthread -pg
```
Both have the same results.
I notice that my gmon.out file is only 687 bytes which seems low.
|
This is a glibc bug/limitation:
-pg -pie doesn't work
If you cannot install a fixed glibc, you can link with-no-pieto disable PIE. Your toolchain probably enables PIE automatically.
|
```
#include <stdio.h>
#include <stdlib.h>
char pointer();
void main() {
char*name = "Paz Leviim", **p_name = &name;
*p_name = pointer();
printf("Now it's %s", *p_name);
getchar();
}
char pointer() {
char name_to_main[100];
printf("The value now is Paz Leviim\nPlease set value:");
scanf_s("%[^\n]%*c", &name_to_main,100);
return name_to_main;
}
```
How can I return the value of variable name_to_main to the pointer *p_name?
|
```
#include <stdio.h>
#include <stdlib.h>
char*pointer(char*now);
void main() {
char*name = "Paz Leviim", **p_name = &name;
*p_name = pointer(*p_name);
printf("Now it's %s", *p_name);
getchar();
}
char*pointer(char*now) {
static char name_to_main[100];
printf("The value now is %s\nPlease set value:",now);
scanf_s("%[^\n]%*c", &name_to_main,100);
return name_to_main;
}
```
Now all working :)
|
```
// Sting for the Name
extern const PROGMEM char name[];
//Data structure of the Heap
typedef struct
{
AllocStrategies strategy;
uint16_t size;
MemAddr start;
MemDriver* driver;
const PROGMEM char name[];
}Heap;
```
expected '=', ',', ';', 'asm' or '__ attribute__' before 'char'
Why do i get this error message twice?
|
You forgot to include a file:
```
#include <avr/pgmspace.h>
```
ThePROGMEMattribute that allows you to allocate aconstvariable in program space is defined there.
You are getting this error message twice because you are usingPROGMEMtwice.
|
This question already has answers here:Compiler warning - suggest parentheses around assignment used as truth value(3 answers)Closed5 years ago.
While looking into a piece of code, I saw this line:
```
if ((b = a)) { /* statements */ }
```
Reading the context, I know its intention is like this:
```
b = a;
if (b != 0) { /* statements */ }
```
I know the two lines above can be simplified into the first code block, but why are the two pair of parentheses? Wouldn't that seem redundant? I think this is totally OK:
```
if (b = a) { /* statements */ }
```
|
Usually one do that to avoid the warning from the compiler, that the assignment is to be (then) evaluated as a condition (in case the developer missed an=in==)
warning: suggest parentheses around assignment used as truth value
Something more indicative,
```
int c = !!(b = a); // condition
if (!!(b = a)) {
```
|
I found this code in the bookserious-cryptography-practical-modern-encryption.
What is nestedfcntldoing?
Getting the file descriptor and Ored it withFD_CLOEXEC, not clear to me what I going on here.
```
#ifndef O_CLOEXEC
fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
```
Other code omitted for clarity.
|
Getting the file descriptor
No, it gets theflagsof the file descriptor. See thefcntl()manual page. The outer call then sets these flags, with additionallyFD_CLOEXECset. This makes sure the file is closed when a function of theexec()family is called (i.e. when the process is replaced with a new program image). This is a security measure, it avoids leaking the opened file accidentally to a program you pass control to withexec*().
It's only done when noO_CLOEXECis available, which allows setting this flag already when opening the file.
|
A session in Linux can have a controlling terminal.
What I am interested in knowing is when you set theforeground process group(usingtcsetpgrp()) of a controlling terminal, is the variable that holds the process group id of theforeground process groupbelongs to the controlling terminal data structures or does it belong to the session data structures?
|
tcsetpgrp()is implemented via the ioctlTIOCSPGRPon the tty device.
This ioctl in turn is implemented in the kernel functiontiocspgrp, sets memberpgrpof thestruct tty_structfor the terminal.
In short, the foreground process group is stored in the tty data structure. Which makes sense, since the effect of the foreground process group is to identify which process(es) will receive signals from the tty when the user presses key combinations such as ctrl-C and ctrl-Z.
|
Does C compiler cache a header file and parse it only once if the file starts with a comment?
```
// Some comment
#ifndef HEADER_GUARD
#define HEADER_GUARD
#endif
```
The question is about compilers, that can cache headers to not parse them more than once.
|
Yes, this optimization is done.gccdocuments it quite explicitly here:https://gcc.gnu.org/onlinedocs/cppinternals/Guard-Macros.html
Basically, if you have a well-written include guard,gccwon't touch the header twice. And a comment outside of the include guard does not stop the optimization (it would be worthless otherwise with all the license comments that precede virtually all open-source header files).
|
how to get bluetooth address of same device either through command line or program
|
Two problems: First is that you never check for errors from any of the system calls.
The second is that the child process shouldterminatewhich yours doesn't. Instead your child process continues in the loop and callaccepton the listening socket and so on, fighting with the parent process about connections. When the child process is done it should callexitto terminate.
|
```
#include<stdio.h>
void main()
{
char str1[100];
char str2[100];
printf("\n Enter the first String\n");
scanf("%[^\n]s",str1);
printf("Enter the second String");
scanf("%[^\n]s",str2);
printf("\n The strings are %s %d \n",str1,i);
}
```
|
Since you want to read a whole line, usefgets. At least you have some control over the string length input, and no need to deal withscanfpeculiarities
```
printf("\n Enter the first String\n");
fgets(str1, 100, stdin);
printf("Enter the second String");
fgets(str2, 100, stdin);
printf("\n The strings are %s %s \n",str1,str2);
```
Note that the trailing\nis still in the strings (if they were 98 chars length max).
Worth reading - scanf vs fgets
|
This question already has answers here:Best practice for compute the function return value(5 answers)Closed5 years ago.
I am trying to get rid of rule 15.5 from my code. This is basically because of multiple returns in the function.
Code looks like:
```
int32_t
do_test(int32_t array[])
{
for(int32_t i=0; i < VAL; i++)
{
if(array[i] == 2) {
return 1;
}
}
return 0;
}
```
I have tried with a temp variable which store the return value and returning this variable at the end. But that didnt work.
Any suggestions ?
|
You need to store a temp variableandto break the loop
```
int32_t
do_test(int32_t array[])
{
int32_t result = 0;
for(int32_t i=0; i < VAL; i++)
{
if(array[i] == 2) {
result = 1;
break; // !!
}
}
return result;
}
```
|
How can I exit the while loop when stdin line is empty?
```
#include <unistd.h>
#include <stdio.h>
int main(){
FILE* stream = popen("sort", "w");
char *line = NULL;
size_t size;
while (getline(&line, &size, stdin)) {
fprintf(stream,"%s\n", line);
}
pclose(stream);
return 0;
}
```
I tried checking the length of line and checking ifgetline != -1and it doesn't work.
|
The problem you have is the newline you read.
if you add
```
if (*line == '\n') break;
```
to your loop, it will probably work as intended.
Testing getline() for a -1 return value is a good idea; you might encounter an End Of File instead of an empty line
|
I'm imagining readingbyte by bytewould be very inefficient, but reading in bulks would almost always read more than needed, requiring to store the rest of the read input in a global context for all subsequent read operations to find. What am I missing?
|
The prototype is:
```
ssize_t getline(char **lineptr, size_t *n, FILE *stream);
```
So it's clearly usingFILE, which is already buffered. So reading character-by-character is not inefficient at all.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.